Easy to understand 28ms java solution


  • 0
    S
    class Solution {
        public String addStrings(String num1, String num2) {
            int m = num1.length(), n = num2.length();
            int[] pos = new int[Math.max(m, n) + 1];
    
            int i = m - 1, j = n - 1;
            int sum = 0, tmp = 0;
            while (i >= 0 || j >= 0) {
                if (i>=0 && j>=0) {
                    sum = (num1.charAt(i) - '0') + (num2.charAt(j) - '0');
                    pos[Math.max(i, j)+1] = (sum + tmp) % 10;
                    tmp = (sum + tmp) / 10;
                }else if (i>=0) {
                    sum = (num1.charAt(i) - '0');
                    pos[i+1] = (sum + tmp) % 10;
                    tmp = (sum + tmp) / 10;
                }else if (j>=0) {
                    sum = (num2.charAt(j) - '0');
                    pos[j+1] = (sum + tmp) % 10;
                    tmp = (sum + tmp) / 10;
                }
    
                i--;
                j--;
            }
    
            StringBuffer res = new StringBuffer();
            if (tmp != 0) res.append(tmp);
            for (int k = 1; k<pos.length; k++) {
                res.append(pos[k]);
            }
    
            return res.toString();
        }
    }

Log in to reply
 

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