Posted on

Description

Submission

class Solution {
public:
    string addStrings(string num1, string num2) {
        int carry = 0;
        if(num1.size() < num2.size()) swap(num1, num2);
        reverse(num1.begin(), num1.end());
        reverse(num2.begin(), num2.end());
        stringstream ss;
        
        int i = 0;
        for(; i < num2.size(); ++i) {
            int sum = num2[i] - '0' + num1[i] - '0' + carry;
            carry = 0;
            if(sum >= 10) {
                sum -= 10;
                carry = 1;
            } 
            ss << sum;
        }

        for(; i < num1.size(); ++i) {
            int sum = num1[i] - '0' + carry;
            carry = 0;
            if(sum >= 10) {
                sum -= 10;
                carry = 1;
            }
            ss << sum;
        }

        if(carry > 0) {
            ss << 1;
        }

        string ret =  ss.str();
        reverse(ret.begin(), ret.end());
        return ret;
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *