Clean C++ with comments. One pass without reversing string.


  • 1
    string addStrings(string num1, string num2) {
            if (num1.length() < num2.length()) {                                // use num1 for result variable
                return addStrings(num2, num1);                                  // make sure num1 is no shorter than num2
            }
            
            int carry = 0;                                                      // carry on value
            for (int i1 = num1.length() - 1, i2 = num2.length() - 1; i2 >= 0 || (carry && i1 >= 0); i1--, i2--) {
                carry += (num1[i1] - '0') + (i2 >= 0 ? num2[i2] - '0' : 0);     // need to check i2 because num2 may be exhausted
                num1[i1] = (carry % 10) + '0';                                  // update result
                carry /= 10;                                                    // update carry on value
            }
            
            return carry ? '1' + num1 : num1;                                   // don't forget the last carry on value
    }
    

Log in to reply
 

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