解题思路:
两种思路,一:从右往左依次加,然后用StringBuilder从左往右存数,之后翻转返回。二:使用栈,之后就不用翻转返回了。
代码: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思路一:从右往左加,从左往右存,翻转返回
public String addStrings(String num1, String num2) {
if(num1 == null) return num2;
if(num2 == null) return num1;
StringBuilder sb = new StringBuilder();
int i = num1.length() - 1,j = num2.length() - 1,carry = 0;
while(i>= 0 || j >= 0 || carry != 0){
carry += i>=0 ? num1.charAt(i--) - '0' : 0;
carry += j>=0 ? num2.charAt(j--) - '0' : 0;
sb.append(carry%10);
carry = carry / 10;
}
return sb.reverse().toString();
}
思路二:使用栈
public String addStrings(String num1, String num2) {
if(num1 == null) return num2;
if(num2 == null) return num1;
Stack<Integer> stack = new Stack<>();
StringBuilder sb = new StringBuilder();
int i = num1.length() - 1,j = num2.length() - 1,carry = 0;
while(i>= 0 || j >= 0 || carry != 0){
carry += i>=0 ? num1.charAt(i--) - '0' : 0;
carry += j>=0 ? num2.charAt(j--) - '0' : 0;
stack.push(carry%10);
carry = carry / 10;
}
while(!stack.isEmpty()){
sb.append(stack.pop());
}
return sb.toString();
}