1
2
3
4
5
6
|
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.
|
题意:字符串做加法。但是不能用内置的函数直接做。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
public
class
Solution {
public
String addStrings(String num1, String num2) {
int
i=num1.length()-
1
;
int
j=num2.length()-
1
;
//http://blog.csdn.net/kingzone_2008/article/details/9220691
StringBuilder ret=
new
StringBuilder();
int
carry=
0
;
while
(i>=
0
|| j>=
0
){
///这里避免了两个字符串长度不一的情况下
int
sum1=i>=
0
?num1.charAt(i--)-
'0'
:
0
;
int
sum2=j>=
0
?num2.charAt(j--)-
'0'
:
0
;
int
sum=sum1+sum2+carry;
carry=sum/
10
;
ret.append(sum%
10
);
}
if
(carry>
0
){
ret.append(
1
);
}
return
ret.reverse().toString();
}
}
|
PS:直接从低位开始求就行。参考大神的。。。。。。。。。。。
本文转自 努力的C 51CTO博客,原文链接:http://blog.51cto.com/fulin0532/1891197