[Leetcode] 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.

 

大数乘法,注意前置0的处理。

 

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         string num3;
 5         num3.resize(num1.size() + num2.size());
 6         reverse(num1.begin(), num1.end());
 7         reverse(num2.begin(), num2.end());
 8         int carry = 0;
 9         int val;
10         int i, j, k;
11         for (i = 0; i < num3.size(); ++i) {
12             num3[i] = '0';
13         }
14         for (i = 0; i < num1.size(); ++i) {
15             carry = 0;
16             for (j = 0; j < num2.size(); ++j) {
17                 val = (num3[i+j] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
18                 carry = val / 10;
19                 val %= 10;
20                 num3[i+j] = '0' + val;
21             }
22             num3[i + j] = '0' + carry;
23         }
24         int prezero = 0;
25         for (i = num3.size() - 1; i > 0; --i) {
26             if (num3[i] == '0') 
27                 prezero++;
28             else 
29                 break;
30         }
31         num3.resize(num3.size() - prezero);
32         reverse(num3.begin(), num3.end());
33         return num3;
34     }
35 };

 

posted @ 2014-03-31 00:58  Eason Liu  阅读(211)  评论(0编辑  收藏  举报