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.
There are 2 things to note in this problem:
- Use StringBuilder to concatenate string is much more efficient (Do need to reverse it for the right order)
- No need to separate the for-loop, just check if the pointer exceed boundary, if so, just set number = 0
class Solution {
public String addStrings(String num1, String num2) {
char[] c1 = num1.toCharArray();
char[] c2 = num2.toCharArray();
int n1=0, n2=0, carry=0;
StringBuilder res = new StringBuilder();
for(int i=c1.length-1,j=c2.length-1;i>-1||j>-1||carry>0;i--,j--){
n1=(i>-1)?c1[i]-'0':0;
n2=(j>-1)?c2[j]-'0':0;
int sum = n1+n2+carry;
if(sum>9) {
carry=1;
res.append(sum%10);
}else{
carry=0;
res.append(sum);
}
}
return res.reverse().toString();
}
}