easy C++ solution


  • 0
    A
    class Solution {
    public:
        string addStrings(string num1, string num2) {
            string ans;
            int i = num1.size() - 1, j = num2.size() - 1, carry = 0;
            while (i >= 0 || j >= 0 || carry) {
                int s = (i >= 0 ? num1[i] - '0' : 0) + (j >= 0 ? num2[j] - '0' : 0) + carry;
                carry = s / 10;
                ans.push_back(s % 10 + '0');
                if (i >= 0)
                    --i;
                if (j >= 0)
                    --j;
            }
            reverse(ans.begin(), ans.end());
            return ans;
        }
    };
    

Log in to reply
 

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