-
Notifications
You must be signed in to change notification settings - Fork 0
/
addStrings*
49 lines (43 loc) · 1.18 KB
/
addStrings*
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/********************************/
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.
Note:
The length of both num1 and num2 is < 5100.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
/******************************/
class Solution
{
public:
string addStrings(string num1, string num2)
{
string num;
int length1 = num1.length();
int length2 = num2.length();
int carry = 0;
for (int i = length1 - 1, j = length2 - 1; i >= 0 || j >= 0; --i, --j)
{
int temp = 0;
if (i >= 0)
{
temp += num1[i] - '0';
}
if (j >= 0)
{
temp += num2[j] - '0';
}
if (carry)
{
++temp;
}
carry = temp / 10;
temp = temp % 10;
num = char(temp + '0') + num;
}
if (carry)
{
num = char(carry + '0') + num;
}
return num;
}
};