My C++ code, 8 ms, quite standard solution


  • 1
    D

    Quite standard, just do it in the way we do multiply operation. The only corner case to deal is "0". O(m+n) time

    class Solution {
    public:
        string multiply(string num1, string num2) {
            int s1L = num1.size(), s2L = num2.size(), i, j, k, carrier=0, temp;
            if(num1=="0" || num2=="0") return "0";
            string res(s1L+s2L, '0');
            
            for(j=s2L-1; j>=0;--j)
            {   
                if(num2[j]=='0') continue;
                for(carrier=0, i=s1L-1; i>=0;--i)
                {
                    temp = carrier + (num2[j]-'0') * (num1[i]-'0') + res[i+j+1]-'0';
                    res[i+j+1] = '0' + temp % 10;
                    carrier = temp/10;
                }
                res[j] = carrier+'0';
            }
            if(carrier) return res;
            else return res.substr(1);
            
        }
    };

Log in to reply
 

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