My c++ code,quite short and easy using index to help determine digit position.


  • 1
    C
    class Solution {
    public:
        string multiply(string num1, string num2) {
            if(num1=="0"||num2=="0") return "0";
            string s="";
            vector<int> v(num1.size()+num2.size(),0);
            string numb1(num1.rbegin(),num1.rend());
            string numb2(num2.rbegin(),num2.rend());
            for(int i=0;i<numb1.size();++i){
                int a=numb1[i]-'0';
                for(int j=0;j<numb2.size();++j){
                    int b=numb2[j]-'0';
                    int c=v[i+j];
                    v[i+j]=(c+a*b)%10;
                    v[i+j+1]+=(c+a*b)/10;
                }
            }
            int k=numb1.size()+numb2.size()-1;
            if(v[k]>0) s+=v[k]+'0';
            for(int i=k-1;i>=0;--i)
                s+=v[i]+'0';
            return s;
        }
    };

Log in to reply
 

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