415. Add Strings

Problem:

Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.

Note:

  1. The length of both num1 and num2 is < 5100.
  2. Both num1 and num2 contains only digits 0-9.
  3. Both num1 and num2 does not contain any leading zero.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
  5. </ol> </p>

    Solutions:

    class Solution {
    public:
        string addStrings(string num1, string num2) {
            string ret;
            int carry = 0;
            int i1 = num1.length() - 1;
            int i2 = num2.length() - 1; 
    
            while (carry != 0 || i1 >= 0 && i2 >= 0) {
                int value = carry + (i1 >= 0 ? num1[i1--] - '0': 0) + (i2 >= 0 ? num2[i2--] - '0' : 0);
                ret.push_back(value % 10 + '0');
                carry = value / 10;
            }
    
            reverse(ret.begin(), ret.end());
    
            if (i1 >= 0) {
                ret = num1.substr(0, i1 + 1) + ret;
            }
    
            if (i2 >= 0) {
                ret = num2.substr(0, i2 + 1) + ret;
            }
    
            return ret;
    
        }
    };
    

    results matching ""

      No results matching ""