Java 9 lines 22ms using char array


  • 0
    Q
    public String addStrings(String num1, String num2) {
        int carry = 0, m = num1.length(), n = num2.length(), len = m<n?n:m;
        char[] res = new char[len+1];
        for(int i=0; i<=len ;i++) {
            int a = i<m ? (num1.charAt(m-i-1) - '0') : 0;
            int b = i<n ? (num2.charAt(n-i-1) - '0') : 0;
            res[len-i] = (char)((a+b+carry)%10 + '0');
            carry = (a+b+carry)/10;
        }
        return res[0]=='0'? new String(res, 1, len) : new String(res, 0, len+1);
    }

Log in to reply
 

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