【Leetcode】【Medium】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.

 

解题:

模拟乘法运算,可以完全按照模拟的思路,用num1的每一位乘num2,得到的数组按位保存在结果字符串中,并不断更新。

先把字符串反转,在逻辑上思路会更加清晰,当然不反转也可以。

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         reverse(num1.begin(), num1.end());
 5         reverse(num2.begin(), num2.end());
 6         int l1 = num1.size();
 7         int l2 = num2.size();
 8         string res(l1 + l2, '0');
 9         int carry, d;
10         
11         for (int i = 0; i < l1; ++i) {
12             int n1 = num1[i] - '0';
13             carry = 0;
14             for (int j = 0; j < l2; ++j) {
15                 int n2 = num2[j] - '0';
16                 d = n1 * n2 + carry + (res[i+j] - '0');
17                 carry = d / 10;
18                 res[i+j] = '0' + (d - carry * 10);
19             }
20             
21             int idx = 0;
22             while (carry != 0) {
23                 d = (res[i+l2+idx] - '0') + carry;
24                 carry = d / 10;
25                 res[i+l2] = '0' + (d - carry * 10);
26                 idx++;
27             }
28         }
29         
30         while (!res.empty() && res.back() == '0') 
31             res.pop_back();
32         if (res.empty()) 
33             return "0";
34         reverse(res.begin(), res.end());
35         return res;
36     }
37 };

 

posted @ 2015-03-10 02:04  胡潇  阅读(182)  评论(0编辑  收藏  举报