415

difficulty: Easy

section pre{ background-color: #eee; border: 1px solid #ddd; padding:10px; border-radius: 5px; }

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.

  2. Both num1 and num2 contains only digits 0-9.

  3. Both num1 and num2 does not contain any leading zero.

  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

Method One

class Solution {
    public String addStrings(String num1, String num2) {
        StringBuilder ans = new StringBuilder();
        char[] chars1 = num1.toCharArray();
        char[] chars2 = num2.toCharArray();
        int p1 = chars1.length -1;
        int p2 = chars2.length -1;
        int carry = 0;
        while(p1 > -1 || p2 > -1){
            int n1 = p1 < 0 ? 0: chars1[p1] - '0';
            int n2 = p2 < 0 ? 0: chars2[p2] - '0';
            int sum = n1 + n2 + carry;
            carry = sum/10;
            ans.insert(0,sum%10);
            p1--;
            p2--;
        }
        if(carry > 0){
            ans.insert(0, 1);
        }
        return String.valueOf(ans);
    }
}

Last updated

Was this helpful?