Given two non-negative integers 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.
Thinking Process
- Scan the two strings from tail towards the head, just like 1st grade math class
- Terminate the loop until stirngs are depeleted and carry bit is 0
public String addStrings(String num1, String num2) {
int carry = 0;
StringBuilder sb = new StringBuilder();
int l1 = num1.length() - 1;
int l2 = num2.length() - 1;
while(l1 >= 0 || l2 >= 0 || carry == 1){
int a = (l1 >= 0) ? Character.getNumericValue(num1.charAt(l1--)) : 0;
int b = (l2 >= 0) ? Character.getNumericValue(num2.charAt(l2--)) : 0;
int sum = a + b + carry;
if(sum < 10){
sb.append(sum);
carry = 0;
}else{
sb.append(sum - 10);
carry = 1;
}
}
return sb.reverse().toString();
}
Complexity
- Array is scanned once, time complexity is O(n)
- The result is stored in a new string, hence space complexity is O(n)