3ms C++ Recursive Solution


  • 0
    F
    string addStrings(string num1, string num2) {
            //find smaller string, append zeros to the front to equal distance
            if(num1.size() < num2.size()) num1.insert(0, num2.size()-num1.size(), '0');
            if(num2.size() < num1.size()) num2.insert(0, num1.size()-num2.size(), '0');
            
            addStringsHelper(&num1, &num2, num1.size()-1, 0);
            return num1;
        }
        
        void addStringsHelper(string* num1, string* num2, int i, int carryover){
            if(i<0){
              if(carryover) (*num1).insert(0, 1, '1');
              return;
            } 
            int sum = (*num1).at(i) + (*num2).at(i) - '0'*2 + carryover;
            
            if(sum<=9){
                (*num1).at(i)='0'+sum;
                addStringsHelper(num1, num2, i-1, 0);
            }
            else{
                (*num1).at(i)='0'+sum-10;
                addStringsHelper(num1, num2, i-1, 1);
            }
        }
    

    Very similar to an iterative version


Log in to reply
 

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