415. 字符串相加
为保证权益,题目请参考 415. 字符串相加(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
class Solution
{
public:
string addStrings(string num1, string num2)
{
if (num1 == "0")
{
return num2;
}
if (num2 == "0")
{
return num1;
}
string ans = "";
while(num1.length() > num2.length())
{
num2 = '0' + num2;
}
while(num1.length() < num2.length())
{
num1 = '0' + num1;
}
int adds = 0;
for (int i = num1.length() - 1; i >= 0; --i)
{
int tmp = (num1[i] - '0') + (num2[i] - '0') + adds;
ans = char(tmp % 10 + '0') + ans;
adds = tmp / 10;
}
if (adds)
{
ans = char(adds + '0') + ans;
}
return ans;
}
};
int main()
{
Solution so;
cout << so.addStrings("999", "111");
return 0;
}
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
50
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
50