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 { public: void Plus(string& a,string& b,string& temp){ int small=min(a.length(),b.length()); bool flag=false; int i=0; for(;i<small;i++){ temp[i]=a[i]+b[i]-'0'; if(flag)temp[i]++; if(temp[i]>'9'){ temp[i]-=10; flag=true; } else{ flag=false; } } while(i<a.length()){ temp[i]=a[i]; if(flag)temp[i]++; if(temp[i]>'9'){ temp[i]-=10; flag=true; } else{ flag=false; } i++; } while(i<b.length()){ temp[i]=b[i]; if(flag)temp[i]++; if(temp[i]>'9'){ temp[i]-=10; flag=true; } else{ flag=false; } i++; } if(flag){ temp[i]='1'; i++; } a.resize(i); for(int j=0;j<i;j++)a[j]=temp[j]; } void MultiplyByNum(string& a,int val,int tens,string&temp){ int j=0; for(;j<tens;j++){ temp[j]='0'; } int f=0; for(int i=0;i<a.length();i++,j++){ int c=(a[i]-'0')*val; c+=f; temp[j]=c%10+'0'; f=c/10; } while(f!=0){ temp[j]=f%10+'0'; f=f/10; j++; } a.resize(j); for(int i=0;i<j;i++)a[i]=temp[i]; } string multiply(string num1, string num2) { // Note: The Solution object is instantiated only once and is reused by each test case. string temp; if(num1.length()==0||num2.length()==0)return "0"; temp.resize(num1.length()+num2.length()+1); for(int i=0;i<num1.size()/2;i++){ char c=num1[i]; num1[i]=num1[num1.size()-1-i]; num1[num1.size()-1-i]=c; } for(int i=0;i<num2.size()/2;i++){ char c=num2[i]; num2[i]=num2[num2.size()-1-i]; num2[num2.size()-1-i]=c; } string p; string sum; for(int i=0;i<num2.length();i++){ int val=num2[i]-'0'; if(val!=0){ p=num1; MultiplyByNum(p,val,i,temp); Plus(sum,p,temp); } } if(sum=="")return "0"; bool allzero=true; for(int i=0;i<sum.length();i++){ if(sum[i]!='0'){ allzero=false; break; } } if(allzero)return "0"; for(int i=0;i<sum.size()/2;i++){ char c=sum[i]; sum[i]=sum[sum.size()-1-i]; sum[sum.size()-1-i]=c; } return sum; } };