Java Beats 99.18% (20ms)


  • 0
    K

    class Solution {

    public String addStrings(String num1, String num2) {
        int len1 = num1.length();
        int len2 = num2.length();
        int lenMax = Math.max(len1, len2);
        
        char[] res = new char[lenMax];
        short n1, n2, sum, carry = 0;
        
        for (int i = lenMax - 1; i >= 0; i--) {
            n1 = (len1 > 0) ? (short) (num1.charAt(--len1) - '0') : 0;
            n2 = (len2 > 0) ? (short) (num2.charAt(--len2) - '0') : 0;
            sum = (short) (n1 + n2 + carry);
            carry = (short) (sum / 10);
            res[i] = (char) ('0' + (sum % 10));
        }
        if (carry > 0) {
            return "1" + String.valueOf(res);
        }
        return String.valueOf(res);
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.