Easy Java Solution - Store digits at Char Array


  • 0
    S
    public String addStrings(String num1, String num2) {
            int i = num1.length() - 1, j = num2.length() - 1, carry = 0;
            char[] res = new char[Math.max(num1.length(), num2.length())];
            int pos = res.length - 1;
            while (i >= 0 || j >= 0) {
                int one = i >= 0 ? num1.charAt(i) - '0' : 0, sec = j >= 0 ? num2.charAt(j) - '0' : 0;
                int sum = one + sec + carry;
                res[pos--] = (char) (sum % 10 + '0');
                i--;
                j--;
                carry = sum / 10;
            }
            if (carry == 1) 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.