码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode – Refresh – Multiply Strings

时间:2015-03-21 09:45:21      阅读:117      评论:0      收藏:0      [点我收藏+]

标签:

Notes:

1. Dont have to allocate l1*l2, just l1+l2 is fare enough.

2. remember i--, j--.

3. upgrade[i+j] is += not = rec[i+j+1]/10;

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         int l1 = num1.size(), l2 = num2.size();
 5         if (l1 == 0 || l2 == 0 || num1 == "0" || num2 == "0") return "0";
 6         vector<int> rec(l1+l2, 0);
 7         unordered_map<int, int> upgrade;
 8         string result;
 9         for (int i = l1-1; i >= 0; i--) {
10             for (int j = l2-1; j >=0; j--) {
11                 rec[i+j+1] += int(num1[i] - 0) * int(num2[j] - 0);
12                 rec[i+j+1] += upgrade[i+j+1];
13                 upgrade[i+j+1] = 0;
14                 upgrade[i+j] += rec[i+j+1]/10;
15                 rec[i+j+1] %= 10;
16                 if (i == 0 && j == 0 && upgrade[0]) rec[0] = upgrade[0];
17             }
18         }
19         bool flag = true;
20         for (int i = 0; i < l1+l2; i++) {
21             if (flag && rec[i] == 0) continue;
22             else flag = false;
23             result += char(rec[i] + 0);
24         }
25         return result;
26     }
27 };

 

LeetCode – Refresh – Multiply Strings

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4355144.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!