c++ solution (O(n))


  • 0
    string addStrings(string num1, string num2) {
        int n = num1.size() - 1, m = num2.size() - 1, c = 0;
        string res;
        while (n >= 0 || m >= 0) {
            int x = ((n >= 0) ? num1[n--] - '0' : 0) + ((m >= 0) ? num2[m--] - '0' : 0) + c;
            c = x / 10;
            res += (x % 10) + '0';
        }
        if (c > 0) res += c + '0';
        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.