similar logic but why is this code so slow, only beats 0.8%


  • 0
    A

    class Solution {
    public:
    string addStrings(string num1, string num2) {

        bool carry = false;
        string resSum, resCarry;
        string big = num1.size() > num2.size() ? num1 : num2;
        string small = num1.size() <= num2.size() ? num1 : num2;
        int bigSize = big.size();
        int smallSize = small.size();
        for(int i = 1; i <= smallSize; i++){
            int sum = big[bigSize - i] - '0' + small[smallSize - i] - '0';
            sum += carry;
            carry = (sum >= 10);
            resSum += char(sum%10 + 48);
        }
        string bigSub = big.substr(0,bigSize-smallSize);
        if(carry){
          resCarry = addStrings( bigSub, "1");
        }
        else resCarry = bigSub;
        reverse(resSum.begin(), resSum.end());
        return resCarry + resSum;        
    }
    

    };


Log in to reply
 

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