c++ right to left addition + reversal concise accepted solution


  • 0
    I
        string addStrings(string num1, string num2) {
            string res;
            int carry = 0;
            int i = num1.size() - 1;
            int j = num2.size() - 1;
            while(i >= 0 || j >= 0)
            {
                int now = (i >= 0 ? num1[i] : '0') + (j >= 0 ? num2[j] : '0') - '0'*2 + carry;
                res.push_back('0' + now%10);
                carry = now/10;
                --i,--j;
            }
            if(carry)
               res.push_back('1');
            reverse(res.begin(), res.end());
            return res;
        }

Log in to reply
 

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