[Leetcode 90] 43 Multiply Strings

Problem:

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.

 

Analysis:

It's the big number simulation problem. Recall the process how we compute the multiplication manually. Multiply the tow numbers digit by digit and sum the result up. Use a char array to store the result reversely and after the computing reverse it to the normal order. Pay attention of the carry bit and the space allocated to the result array (l1+l2+1 is definitely enough but l1+l2 is not). Also, if one of the given number is 0, just return 0 and don't bother to compute it even.

 

Code:

 1 class Solution {
 2 public:
 3    string multiply(string num1, string num2) {
 4     // Start typing your C/C++ solution below
 5     // DO NOT write int main() function
 6     if (num1 == "0" || num2 == "0")
 7         return "0";
 8     
 9     int l1 = num1.length(), l2 = num2.length(), idx, cry;
10     char *res = new char[l1+l2+1];
11 
12     for (int i=0; i<l1+l2; i++)
13         res[i] = '0';
14 
15     for (int i=l1-1, inc=0; i>=0; i--, inc++) {
16         idx = inc, cry = 0;
17         for (int j=l2-1; j>=0; j--) {
18             int mul = (num1[i]-'0') * (num2[j]-'0') + cry + (res[idx]-'0');
19 
20             res[idx] = ( mul % 10 ) + '0';
21             cry = mul / 10;
22             idx++;
23         }
24 
25         if (cry > 0)
26             res[idx] = cry + '0';
27     }
28 
29     if (cry > 0)
30         res[idx++] = cry + '0';
31 
32     res[idx] = '\0';
33 
34     for (int i=0, j=idx-1; i < j; i++, j--) {
35         char t = res[i];
36         res[i] = res[j];
37         res[j] = t;
38     }
39 
40     string r(res);
41 
42     return r;
43 }
44 };
View Code

 

posted on 2013-07-27 08:02  freeneng  阅读(226)  评论(0编辑  收藏  举报

导航