Leetcode Multiply Strings 43

来源:互联网 发布:电脑的网络有个感叹号 编辑:程序博客网 时间:2024/05/29 10:12

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note:
The numbers can be arbitrarily large and are non-negative.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
Subscribe to see which companies asked this question

题目链接

模拟~

class Solution {public:    string multiply(string num1, string num2) {        int len1=num1.length();        int len2=num2.length();        string ans="";        string temp_ans="";        for(int i=len2-1;i>=0;i--){            int shift=len2-1-i;            temp_ans=mul(num1,(int)num2[i]-'0');            //cout<<"temp_ans"<<temp_ans<<endl;            temp_ans=reverse(temp_ans);            for(int j=0;j<shift;j++){                temp_ans=temp_ans+'0';            }            //cout<<"shift:" <<temp_ans<<endl;            ans=add(ans,temp_ans);            //cout<<"ans="<<ans<<endl;        }        bool mark=true;        for(int i=0;i<ans.length();i++){            if(ans[i]!='0'){                mark=false;                break;            }        }        if(mark) ans="0";        return ans;    }    string reverse(string s){        int len=s.length();        int l=0,r=len-1;        while(l<r){            s[l]^=s[r];            s[r]^=s[l];            s[l]^=s[r];            l++;            r--;        }        return s;    }    string mul(string s,int d){        int len=s.length();        int carry=0,temp=0,r=0;        string ans="";        for(int i=len-1;i>=0;i--){            temp=((int)(s[i]-'0'))*d+carry;            r=temp%10;            carry=temp/10;            ans+=to_string(r);        }        if(carry) ans+=to_string(carry);        return ans;    }    string add(string a,string b){        int la=a.length();        int lb=b.length();        string ans="";        int carry=0,temp=0,r=0,i,j;        for(i=la-1,j=lb-1;i>=0 && j>=0;i--,j--){            temp=(int)(a[i]-'0')+(int)(b[j]-'0')+carry;            r=temp%10;            carry=temp/10;            ans+=to_string(r);        }        for(;i>=0;i--){            temp=(int)(a[i]-'0')+carry;            r=temp%10;            carry=temp/10;            ans+=to_string(r);        }        for(;j>=0;j--){            temp=(int)(b[j]-'0')+carry;            r=temp%10;            carry=temp/10;            ans+=to_string(r);        }        if(carry) ans+='1';        ans=reverse(ans);        //cout<<"a="<<a<<" b="<<b<<" ans="<<ans<<endl;        return ans;    }};
0 0
原创粉丝点击