Iterative - Java - Simple - 24 ms


  • 0
    public String addStrings(String num1, String num2) 
        {
            int carry = 0;
            int i = num1.length()-1;
            int j = num2.length()-1;
            StringBuilder ans = new StringBuilder();
            while(i >= 0 || j >= 0)
            {
                int sum = 0, a_i = 0, b_j = 0;
                // check if we still have chars in sttring 1
                if (i >= 0)
                    a_i = num1.charAt(i) - '0';
                // check if we still have chars in sttring 2
                if (j >= 0)
                    b_j = num2.charAt(j) - '0';
                sum = a_i + b_j + carry;
                carry = sum/10;
                ans.append(sum%10);
                i--;j--;
            }
            if (carry > 0)
                ans.append(carry);
            return ans.reverse().toString();
        }

Log in to reply
 

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