Multiply Strings
Multiply Strings
Not a hard problem
Pay attention to the carryer!
1 class Solution {
2 public:
3 string multiply(string num1, string num2) {
4 int l1 = num1.length();
5 int l2 = num2.length();
6 int l3 = l1+l2;
7 int result[l1+l2];
8 memset(result,0,sizeof(result));
9 int carryer = 0;
10 int t = 0;
11 for ( int i = 0; i < l1; i++ ) {
12 carryer = 0;
13 for ( int j = 0; j < l2; j++ ) {
14 t = (num1[l1-1-i]-'0')*(num2[l2-1-j]-'0')+carryer+result[l3-1-i-j];
15 result[l3-1-i-j] = t%10;
16 carryer = t/10;
17 }
18 result[l3-1-i-l2] += carryer;
19 }
20 string re = "";
21 char ch;
22 int i = 0;
23 while ( i < l3 && result[i] == 0 ) {
24 i++;
25 }
26 if ( i == l3 ) {
27 return "0";
28 }
29 for ( ; i < l3; i++ ) {
30 ch = '0'+result[i];
31 re += ch;
32 }
33 return re;
34 }
35 };