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

LeetCode OJ:Multiply Strings (字符串乘法)

时间:2015-10-11 22:45:09      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

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 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         if(num1 == "0" || num2 == "0") return "0";
 5         int steps = 0;
 6         int pos = 0;
 7         int flag = 0;
 8         int val = 0;
 9         string result = "";
10         reverse(num1.begin(), num1.end());
11         reverse(num2.begin(), num2.end());
12         int len1 = num1.length();
13         int len2 = num2.length();
14         for(int i = 0; i < len1; ++i){
15               pos = steps;
16             for(int j = 0; j < len2; ++j){
17                 val = (num1[i] - 0)*(num2[j] - 0) + flag;
18                 if(result.size() <= pos){
19                     result.append(1, val%10 + 0);
20                 }else{
21                     val += (result[pos] - 0);
22                     result[pos] = val%10 + 0;
23                 }
24                 flag = val/10;
25                 pos++;  
26             }
27             if(flag > 0)
28                 result.append(1, flag + 0);
29             flag = 0;
30             steps++;
31         }
32         reverse(result.begin(), result.end());
33         return result;
34     }
35 };

 

LeetCode OJ:Multiply Strings (字符串乘法)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4870089.html

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