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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class Solution {
public String addStrings(String num1, String num2) {
if (num1 == null || num2 == null) {
return null;
}
StringBuilder sb = new StringBuilder();
int carry = 0;
for (int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--) {
int digit1 = (i < 0 ? 0 : num1.charAt(i) - '0');
int digit2 = (j < 0 ? 0 : num2.charAt(j) - '0');
carry += digit1 + digit2;
sb.append(carry % 10);
carry /= 10;
}
if (carry == 1) {
sb.append(carry);
}
return sb.reverse().toString();
}
}