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.

Solution:

public class Solution {
    public String addStrings(String num1, String num2) {
        int n1 = num1.length(), n2 = num2.length();
        if(n1<n2) return addStrings(num2, num1);
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        for(int i=1; i<=n1; i++){
            int a = num1.charAt(n1-i)-'0';
            int b = n2-i<0 ? 0 : num2.charAt(n2-i)-'0';
            sb.insert(0, (a+b+carry)%10);
            carry = (a+b+carry)/10;
        }
        if(carry!=0) sb.insert(0, carry);
        return sb.toString();
    }
}
comments powered by Disqus