LeetCode(43. 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.

思路比较简单,不多说啦

几个需要注意的点:

1. 高位多个为0的,需要进行判断

2. 如果乘数为0的话,可以直接跳过,能节省不少时间

3. string 的两个使用

 1) 创建有 len 长的 ‘0’串  string str(len, '0')

 2) string 的反转 reverse(str.begin(), str.end())  反转后操作好像更容易理解~

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         int size1 = num1.size();
 5         int size2 = num2.size();
 6         string result(size1 + size2 + 1, '0');
 7         reverse(num1.begin(),num1.end());
 8         reverse(num2.begin(), num2.end());
 9         for(int j = 0; j < size2; ++j){//num2
10             if(num2[j] == '0')
11                 continue;
12             int k = j;
13             for(int i = 0; i < size1; ++i){//num1
14                 int tmp = (num1[i] - '0') * (num2[j] - '0') + result[k] - '0';
15                 result[k] = tmp % 10 + '0';
16                 result[k + 1] = result[k + 1] + tmp / 10;
17                 ++k;
18             }
19         }
20         while(!result.empty() && result.back() == '0') result.pop_back();
21         if(result.empty()) return "0";
22         reverse(result.begin(), result.end());
23         return result;
24     }
25 };

 

posted @ 2016-03-29 14:55  huapyuan  阅读(195)  评论(0编辑  收藏  举报