【leetcode】415. Add Strings

描述
将两个字符相加,两个字符代表大整数,有5100多位,不能用int表示。

我的解法

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
class Solution {
public:
string addStrings(string num1, string num2) {
int len1 = num1.size();
int len2 = num2.size();
int maxlen = len1 > len2 ? len1 : len2;
string str_sum ="";
int overflow = 0;
for (int i = 0; i < maxlen; i++) {
int sumtemp = 0;
//common partion
if (i < len1 && i < len2) {
sumtemp = (num1[len1 - i - 1]-'0') + (num2[len2 - i - 1] -'0');
if (overflow == 1) {
sumtemp ++;
overflow = 0;
}
if (sumtemp >= 10) {
overflow = 1;
sumtemp -= 10;
}
}
else if (len1 > len2) {
sumtemp = num1[len1-i-1]-'0';
if (overflow == 1) {
overflow = 0;
sumtemp++;
}
if (sumtemp >= 10) {
sumtemp -= 10;
overflow = 1;
}
}
else if (len1 < len2) {
sumtemp = num2[len2 - i-1]-'0';
if (overflow == 1) {
overflow = 0;
sumtemp++;
}
if (sumtemp >= 10) {
sumtemp -= 10;
overflow = 1;
}
}
str_sum=to_string(sumtemp)+str_sum;
}
if (overflow == 1) { str_sum= "1" + str_sum; }
return str_sum;
}
};

更佳的解法
引用值得学习,overflow的产生值得学习,求余的方式值得学习,采用short和long值得学习。
参考链接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
string addStrings(string num1, string num2) {
string & longstr = (num1.size() > num2.size()) ? num1:num2;
string & shortstr = (num1.size() <= num2.size()) ? num1:num2;
string result = "";
int overflow = 0;
for (int i = longstr.size() - 1, j = shortstr.size() - 1; i >= 0; i--, j--) {
int tempsum = 0;
if (j >= 0) {
tempsum = longstr[i] - '0' + shortstr[j] - '0'+ overflow;
}
else {
tempsum = longstr[i] - '0' + overflow;
}
overflow = tempsum / 10;
result = char(tempsum % 10+'0') + result;
}
if (overflow) {
result = '1' + result;
}
return result;
}
};

参考资料
原题链接