415 Add Strings
Given two non-negative numbers 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.
Company Tag: Google Airbnb
分析
BitInteger的最简单的部分
把两个string反过来,从后往前加,可以学习的地方是对于while的条件可以设置成,index1< len1 || index2 < len2.
然后在内部分别对index1 < len1和index2 <len2处理,这样就不用对其中一个提前结束的情况单独再写一个循环了
`
public String addStrings(String num1, String num2) {
if(num1 == null) {
return num2;
}
if(num2 == null) {
return num1;
}
StringBuilder sb1 = new StringBuilder(num1);
StringBuilder sb2 = new StringBuilder(num2);
int len1 = num1.length();
int len2 = num2.length();
sb1.reverse();
sb2.reverse();
StringBuilder sb = new StringBuilder();
int index1 = 0;
int index2 = 0;
int carry = 0;
while(index1 < len1 || index2 < len2) {
int cur = carry;
if(index1 < len1) {
cur += sb1.charAt(index1++) - '0';
}
if(index2 < len2) {
cur += sb2.charAt(index2++) - '0';
}
if(cur > 9) {
cur %= 10;
carry = 1;
} else {
carry = 0;
}
sb.append(cur);
}
if(carry == 1) {
sb.append(1);
}
return sb.reverse().toString();
}