Multiply Strings
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.
大数的乘法问题,运用乘法规则就好了。
1 class Solution { 2 public: 3 string multiply(string num1, string num2) { 4 if(num1=="0" || num2=="0") return "0"; 5 string result; 6 int len1=num1.length(); 7 int len2=num2.length(); 8 int len=len1+len2; 9 int* n1=new int[len1]; 10 int* n2=new int[len2]; 11 int* multi=new int[len]; 12 for(int i=0;i<len;i++) 13 { 14 multi[i]=0; 15 } 16 for(int i=0;i<len1;i++) 17 { 18 n1[i]=num1[len1-i-1]-'0'; 19 } 20 for(int i=0;i<len2;i++) 21 { 22 n2[i]=num2[len2-i-1]-'0'; 23 } 24 for(int i=0;i<len1;i++) 25 { 26 for(int j=0;j<len2;j++) 27 { 28 multi[i+j]=multi[i+j]+n1[i]*n2[j]; 29 } 30 } 31 for (int i=0;i<len;i++) 32 { 33 int tmp=multi[i]; 34 multi[i]=tmp%10; 35 multi[i+1]+=tmp/10; 36 } 37 int first_nozero; 38 for(int i=len-1;i>=0;i--) 39 { 40 if(multi[i]!=0) 41 { 42 first_nozero=i; 43 break; 44 } 45 } 46 for(int i=first_nozero;i>=0;i--) 47 { 48 result+=char(multi[i]+'0'); 49 } 50 delete []n1; 51 delete []n2; 52 delete []multi; 53 54 return result; 55 } 56 };