Simple Java Solution


  • 0
    D
    public String addStrings(String num1, String num2) {
        StringBuilder sb = new StringBuilder();
        int carry = 0;
        int i = num1.length() - 1;
        int j = num2.length() - 1;
        while (i >= 0 || j >= 0) {
            int digit = carry;
            if (i >= 0) {
                digit += num1.charAt(i--) - '0';
            }
            if (j >= 0) {
                digit += num2.charAt(j--) - '0';
            }
            sb.insert(0, digit % 10);
            carry = digit / 10;
        }
        if (carry != 0) {
            sb.insert(0, carry);
        }
        return sb.toString();
    }

Log in to reply
 

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