Straightforward Java solution with comments


  • 0
    H
      public String addStrings(String num1, String num2) {
            
            if (num1 == null || num2 == null || num1.length() == 0 || num2.length() == 0)
                return "0";
            
            int l1 = num1.length() - 1;
            int l2 = num2.length() - 1;
            int carry = 0;
            
            StringBuilder ret = new StringBuilder();
            
            // calculate the common part where l1 and l2 >= 0
            while (l1 >=0 && l2 >= 0) {
                int cur = num1.charAt(l1)-'0'+num2.charAt(l2)-'0' + carry;
                ret.insert(0, cur % 10+"");
                carry = cur >= 10 ? 1 : 0;
                l1--;
                l2--;
            }
            
            int lr = 0;
            String remain = null;
            
            // if two strings are equal length, stop here
            if (l1 == l2) {        // take care of carry digit
                if (carry > 0)
                    ret.insert(0, "1");
                    
                return ret.toString();
            }
            else if (l1 < l2) {
                remain = num2;
                lr = l2;
            } else {
                remain = num1;
                lr = l1;
            }
            
            // finish the remaining string. Need to consider carry all the time as well
            while (lr >= 0) {
                int cur = remain.charAt(lr)-'0' + carry;
                ret.insert(0, cur % 10 + "");
                carry = cur >= 10 ? 1 : 0;
                lr--;
            }
            
            // take care of carry digit
            if (carry > 0)
                ret.insert(0, "1");
                
            return ret.toString();
        }
    

Log in to reply
 

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