05 August 2008
将两个string形式的非负的十进制数相加,并且保存在string中,从后向前各一个指针
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public String addStrings(String num1, String num2) {
StringBuilder res = new StringBuilder();
int carry = 0;
int p1 = num1.length() - 1;
int p2 = num2.length() - 1;
while (p1 >= 0 || p2 >= 0) {
int x1 = p1 >= 0 ? num1.charAt(p1) - '0' : 0;
int x2 = p2 >= 0 ? num2.charAt(p2) - '0' : 0;
int value = (x1 + x2 + carry) % 10;
carry = (x1 + x2 + carry) / 10;
res.append(value);
p1--;
p2--;
}
if (carry != 0)
res.append(carry);
return res.reverse().toString();
}
}