C++ Solution for Multiply Strings


  • 0
    G
    class Solution {
    public:
        string multiply(string num1, string num2) {
            if(num1.size()==0&&num2.size()==0)return num1;
            vector<int> result(num1.size()+num2.size()-1,0);
            for(int i=num2.size()-1;i>=0;i--){
                int a=result.size()-1-(num2.size()-1-i);
                for(int j=num1.size()-1;j>=0;j--){
                    char c2=num2[i],c1=num1[j];
                    int count=(c2-'0')*(c1-'0');
                    result[a]+=count;
                    a--;
                }
            }
    
            for(int i=result.size()-1;i>=1;i--){
                int a=result[i];
                result[i]=a%10;
                result[i-1]+=a/10;
            }
            string s;
            if(result[0]>9){
                int a=result[0];result[0]=a%10;
                s=to_string(a/10);
                for(int i=0;i<result.size();i++){
                    char c='0'+result[i];
                    s.push_back(c);
                }
                return s;
            }
            int i=0;
            for(;i<result.size();i++){
                if(result[i]!=0)break;
            }
            for(;i<result.size();i++){
                char c='0'+result[i];
                    s.push_back(c);
            }
            if(s.size()==0)s.push_back('0');
            return s;
        }
    };

Log in to reply
 

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