Given two non-negative numbers num1
and num2
represented as string, return the sum of num1
and num2
.
Note:
- The length of both
num1
andnum2
is < 5100. - Both
num1
andnum2
contains only digits0-9
. - Both
num1
andnum2
does not contain any leading zero. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
思路: Two pointers, 就是加法,保持进位,注意是从最后的char开始加的。
class Solution {
public String addStrings(String num1, String num2) {
int carry = 0;
int index1 = num1.length() - 1;
int index2 = num2.length() - 1;
StringBuilder sb = new StringBuilder();
while(carry != 0 || index1 >= 0 || index2 >= 0) {
int cursum = carry;
if(index1 >= 0) {
cursum += num1.charAt(index1) - '0';
index1--;
}
if(index2 >= 0) {
cursum += num2.charAt(index2) - '0';
index2--;
}
carry = cursum / 10;
sb.insert(0, cursum % 10);
}
return sb.toString();
}
}