6-line C++ concise solution


  • 0
        string addStrings(string num1, string num2) {
          if (num1.size() < num2.size()) return addStrings(num2, num1);
          int carry = 0, n1 = num1.size(), dn = n1 - num2.size(), sum;
          for (int i = n1-1; i >= 0 && (carry || i>=dn); --i) {
            carry = (sum = (num1[i]-'0') + carry + (i>=dn? (num2[i-dn]-'0') : 0))/10;
            num1[i] = '0' + sum%10;
          }
          return carry? ("1" + num1) : num1;
        }
    

Log in to reply
 

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