c++ solution


  • 0
    M

    class Solution {
    public:
    string multiply(string num1, string num2) {
    int index1 = num1.size();
    int index2 = num2.size();
    int plus = 0;
    std::string res;
    for(int i=index2-1; i>=0; i--)
    {
    int loc = (index2-1) - i;
    plus = 0;
    for(int j=index1-1; j>=0; j--,loc++)
    {
    int sum = (num2[i]-'0')*(num1[j]-'0') + plus + ((res.size()>loc)?(res[loc]-'0'):0);
    plus = sum / 10;
    if(res.size() > loc)
    res[loc] = sum%10 + '0';
    else
    res.push_back(sum%10 + '0');
    }
    if(plus != 0)
    {
    if(res.size() > loc)
    res[loc] = plus + '0';
    else
    res.push_back(plus + '0');
    }
    }

        while(res.size() && res[res.size()-1]=='0')
            res.pop_back();
        if(!res.size())
            res.push_back('0');
    
        int j=res.size()-1, i=0;
        while(i < j)
        {
            char temp = res[i];
            res[i] = res[j];
            res[j] = temp;
            i++, j--;
        }
        
        return res;
    }
    

    };


Log in to reply
 

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