Intuitively easy to understand yet efficient C++ code (9ms).


  • 0

    My C++ code below runs in 9 ms. I am not doing anything complex - just adding the numbers like they were in our primary classes! Hope this is helpful. Suggestions for improvement are welcome!

    #define toInt(c) c-'0'
    
    class Solution {
    public:
        string addStrings(string num1, string num2) {
            if(num1.empty())
                return num2;
                
            if(num2.empty())
                return num1;
                
            int num1_i=num1.size()-1;
            int num2_i=num2.size()-1;
            int target_i=num1_i>num2_i?num1_i:num2_i;
            target_i++;
            
            vector<char> target(target_i,0);
            target_i--;
            int carry=0;
            while(num1_i>=0 && num2_i>=0) {
                int temp = toInt(num1[num1_i]) + toInt(num2[num2_i]) + carry;
                target[target_i] = (temp%10)+'0';
                carry = temp/10;
                target_i--;
                num1_i--;
                num2_i--;
            }
            
            if(num1_i>=0) {
                while(num1_i>=0) {
                    int temp = toInt(num1[num1_i]) + carry;
                    target[target_i] = (temp%10) + '0';
                    target_i--;
                    num1_i--;
                    carry=temp/10;
                }
            }
            
            if(num2_i>=0) {
                while(num2_i>=0) {
                    int temp = toInt(num2[num2_i]) + carry;
                    target[target_i] = (temp%10) + '0';
                    target_i--;
                    num2_i--;
                    carry=temp/10;
                }
            }
            
            if(carry) {
                target.insert(target.begin(), carry+'0');
            }
            std::string str(target.begin(), target.end());
            
            return str;
        }
    };
    

Log in to reply
 

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