Skip to content

Commit a87f835

Browse files
committed
day 9
1 parent c3b9997 commit a87f835

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
/*
2+
Add Strings
3+
===========
4+
5+
Given two non-negative integers, num1 and num2 represented as string, return the sum of num1 and num2 as a string.
6+
7+
You must solve the problem without using any built-in library for handling large integers (such as BigInteger). You must also not convert the inputs to integers directly.
8+
9+
Example 1:
10+
Input: num1 = "11", num2 = "123"
11+
Output: "134"
12+
13+
Example 2:
14+
Input: num1 = "456", num2 = "77"
15+
Output: "533"
16+
17+
Example 3:
18+
Input: num1 = "0", num2 = "0"
19+
Output: "0"
20+
21+
Constraints:
22+
1 <= num1.length, num2.length <= 104
23+
num1 and num2 consist of only digits.
24+
num1 and num2 don't have any leading zeros except for the zero itself.
25+
*/
26+
27+
class Solution
28+
{
29+
public:
30+
string addStrings(string num1, string num2)
31+
{
32+
reverse(num1.begin(), num1.end());
33+
reverse(num2.begin(), num2.end());
34+
35+
string ans = "";
36+
int carry = 0, i = 0;
37+
38+
while (i < num1.size() || i < num2.size() || carry)
39+
{
40+
int a = (i < num1.size() ? num1[i] - '0' : 0);
41+
int b = (i < num2.size() ? num2[i] - '0' : 0);
42+
43+
int sum = a + b + carry;
44+
int digit = sum % 10;
45+
46+
ans.push_back(digit + '0');
47+
carry = sum / 10;
48+
49+
i++;
50+
}
51+
52+
reverse(ans.begin(), ans.end());
53+
return ans;
54+
}
55+
};

Leetcode Daily Challenge/August-2021/README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@
1010
| 5. | [Stone Game](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3870/) | [cpp](./05.%20Stone%20Game.cpp) |
1111
| 6. | [N-ary Tree Level Order Traversal](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3871/) | [cpp](./06.%20N-ary%20Tree%20Level%20Order%20Traversal.cpp) |
1212
| 7. | [Palindrome Partitioning II](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/613/week-1-august-1st-august-7th/3872/) | [cpp](./07.%20Palindrome%20Partitioning%20II.cpp) |
13+
| 9. | [Add Strings](https://leetcode.com/explore/challenge/card/august-leetcoding-challenge-2021/614/week-2-august-8th-august-14th/3875/) | [cpp](./09.%20Add%20Strings.cpp) |

0 commit comments

Comments
 (0)