C++ solution using vector


  • 1
    M
    class Solution {
    public:
        string addStrings(string num1, string num2) {
        reverse(begin(num1), end(num1));
        reverse(begin(num2), end(num2));
        int len1 = num1.length();
        int len2 = num2.length();
        vector<int> result;
        int pos1 = 0;
        
        int carry = 0;
        int dig_sum = 0;
        while(pos1 < len1 && pos1 < len2){
            dig_sum = (num1[pos1] - '0') + (num2[pos1] - '0') + carry;
            result.push_back(dig_sum % 10);
            carry = (dig_sum >= 10)? 1 : 0;
            pos1++;
        }
        
        if(pos1 < len1){
            for(int i = pos1; i < len1; ++i){
                dig_sum = (num1[i] - '0') + carry;
                result.push_back(dig_sum % 10);
                carry = (dig_sum >= 10)? 1 : 0;
            }
            if(carry > 0){
                result.push_back(1);
                carry = 0;
            }
        }
        
        if(pos1 < len2){
            for(int i = pos1; i < len2; ++i){
                dig_sum = (num2[i] - '0') + carry;
                result.push_back(dig_sum % 10);
                carry = (dig_sum >= 10)? 1 : 0;
            }
            if(carry > 0){
                result.push_back(1);
                carry = 0;
            }
        }
        
        if(carry > 0){
            result.push_back(1);
        }
        
        string ret_str;
        for(auto it = result.begin(); it != result.end(); ++it){
            ret_str += to_string(*it);
        }
        reverse(std::begin(ret_str), std::end(ret_str));
        
        return ret_str;
        }
    };
    

Log in to reply
 

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