Java solution


  • 0
    M
    public class Solution {
        public String addStrings(String num1, String num2) {
            int carry=0, mod, a, b, bit;
            StringBuilder ans = new StringBuilder("");
            for(int i=num1.length()-1, j=num2.length()-1; i>=0 || j>=0; i--, j--){
                if(i>=0) a = num1.charAt(i)-'0';
                else a = 0;
                if(j>=0) b = num2.charAt(j)-'0';
                else b = 0;
                bit = a+b+carry;
                if(bit>=10){ 
                    carry = 1; //carry = bit/10
                    mod = bit-10; // mod = bit%10;
                } else {
                    carry = 0;
                    mod = bit;
                }
                ans.append(mod);
            }
            if(carry>0) ans.append(carry); // carry == 1
            return ans.reverse().toString();
        }
    }
    
    

Log in to reply
 

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