415. Add Strings

Description

Given two non-negative integers 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

class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder sum = new StringBuilder();
        int carry = 0;
        int len1 = num1.length();
        int len2 = num2.length();
        
        for (int i = 0; i < Math.max(len1, len2); ++i) {
            if (i < len1) {
                carry += num1.charAt(len1 - 1 - i) - '0';
            }
            if (i < len2) {
                carry += num2.charAt(len2 - 1 - i) - '0';
            }
            sum.insert(0, carry % 10);
            carry /= 10;
        }
        
        if (carry > 0) {
            sum.insert(0, carry);
        }
        
        return sum.toString();
    }
}

你可能感兴趣的:(415. Add Strings)