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) {
        if(num1 == null || num2 == null) return null;
        int carry = 0;
        int i = 0;
        StringBuilder sb = new StringBuilder();
        while(i < num1.length() || i < num2.length()) {
            int val1 = i < num1.length() ? num1.charAt( num1.length() - 1 - i  )-'0' : 0;
            int val2 = i < num2.length() ? num2.charAt( num2.length() - 1 - i  )-'0' : 0;

            int val = val1 + val2 + carry;
            if(val >= 10) carry = 1;
            else carry = 0;

            val %= 10;
            sb.append(val);
            i++;
        }
        if(carry != 0) sb.append(1);

        return sb.reverse().toString();
    }
}

results matching ""

    No results matching ""