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.
要求:字符串表示的数字可能无穷大,并且非负。
class Solution { private: vector<string> tempStrs; public: string add(string num1,string num2) { int n1=num1.size(); int n2=num2.size(); int i=n1-1;int j=n2-1; string resStr; int jinwei=0; while (i>=0&&j>=0) { int temp=(num1[i]-'0')+(num2[j]-'0')+jinwei; jinwei=temp>=10?1:0; temp%=10; resStr.push_back(temp+'0'); --i; --j; } if(i>=0){ while (i>=0) { int temp=(num1[i]-'0')+jinwei; jinwei=temp>=10?1:0; temp%=10; resStr.push_back(temp+'0'); --i; } } else if(j>=0){ while (j>=0) { int temp=(num2[j]-'0')+jinwei; jinwei=temp>=10?1:0; temp%=10; resStr.push_back(temp+'0'); --j; } } if(jinwei!=0){ resStr.push_back(jinwei+'0'); } reverse(resStr.begin(),resStr.end()); return resStr; } string multiply(string num1, string num2) { if(num1.empty()||num2.empty()) return ""; if(num1=="0"||num2=="0") return "0"; int jinwei=0; int n1=num1.size(); int n2=num2.size(); if(n2>n1){ string temp=num1; num1=num2; num2=temp; n1=num1.size(); n2=num2.size(); } int time=0; string tempStr; string res; for(int i=n2-1;i>=0;--i) { tempStr.clear(); jinwei=0; for(int j=n1-1;j>=0;--j) { int temp=(num1[j]-'0')*(num2[i]-'0')+jinwei; jinwei=temp>=10?(temp/10):0; temp=temp%10; tempStr.push_back(temp+'0'); } if(jinwei!=0){ tempStr.push_back(jinwei+'0'); } reverse(tempStr.begin(),tempStr.end()); for(int q=0;q<time;++q){ tempStr.push_back('0'); } tempStrs.push_back(tempStr); ++time; } if(tempStrs.size()>1){ res=add(tempStrs[0],tempStrs[1]); for (int i=2;i<tempStrs.size();++i) { res=add(res,tempStrs[i]); } return res; }else { return tempStrs[0]; } } };