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.
Solution:
This problem is similar to Add Binary.
We start from the end of the strings and go backward.
Code:
public class Solution { public String addStrings(String num1, String num2) { int len1 = num1.length() - 1; int len2 = num2.length() - 1; int carry = 0; StringBuilder sb = new StringBuilder(); while (carry == 1 || len1 >= 0 || len2 >= 0) { int v1 = len1 >= 0 ? num1.charAt(len1--) - '0' : 0; int v2 = len2 >= 0 ? num2.charAt(len2--) - '0' : 0; int sum = v1 + v2 + carry; sb.append(sum % 10); carry = sum / 10; } return sb.reverse().toString(); } }