C++ self explanatory


  • 0
    Y
        string addStrings(string num1, string num2) {
            int num1_size = num1.size();
            if (!num1_size)
                return num2;
            int num2_size = num2.size();
            if (!num2_size)
                return num1;
            int num_size = max(num1_size, num2_size);
            string ret(num_size + 1, '0');
            reverse(begin(num1), end(num1));
            reverse(begin(num2), end(num2));
            for (int i = 0; i < num_size; ++i) {
                int d = ret[i] - '0';
                d += i < num1_size ? num1[i] - '0' : 0;
                d += i < num2_size ? num2[i] - '0' : 0;
                ret[i] = '0' + d % 10;
                ret[i+1] = '0' + d / 10;
            }
            if (ret[num_size] == '0')
                ret.resize(num_size);
            reverse(begin(ret), end(ret));
            return ret;
        }
    '''

Log in to reply
 

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