11 lines concise and easy understand c++ solution, reverse + rebuild


  • 0
    A
    class Solution {
    public:
        string addStrings(string num1, string num2) {
            string result = "";
            reverse(num1.begin(), num1.end());
            reverse(num2.begin(), num2.end());
            int carry = 0, it1 = 0, it2 = 0;
            while(it1 < num1.size() || it2 < num2.size() || carry > 0) {
                if(it1 < num1.size()) carry += num1[it1++] - '0';
                if(it2 < num2.size()) carry += num2[it2++] - '0';
                result = to_string(carry % 10) + result;
                carry /= 10;
            }
            return result;
        }
    };
    

Log in to reply
 

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