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

Leetcode#43 Multiply Strings

时间:2015-01-27 07:02:41      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

原题地址

 

想当年初学C++的时候写个大整数加法都快屎了,现在觉得自己还是成长了不少哇。

代码:

 1 string multiply(string num1, string num2) {
 2         int len1 = num1.length();
 3         int len2 = num2.length();
 4         vector<int> buffer(len1 + len2, 0);
 5         
 6         for (int i = len1 - 1; i >= 0; i--)
 7             for (int j = len2 - 1; j >= 0; j--)
 8                 buffer[len1 - 1 - i + len2 - 1 - j] += (num1[i] - 0) * (num2[j] - 0);
 9         
10         for (int i = 0, carry = 0; i < len1 + len2; i++) {
11             buffer[i] += carry;
12             carry = buffer[i] / 10;
13             buffer[i] %= 10;
14         }
15         
16         string res;
17         int p = len1 + len2 - 1;
18         while (p >= 0 && buffer[p] == 0) p--;
19         while (p >= 0) {
20             res += buffer[p] + 0;
21             p--;
22         }
23         
24         return res.empty() ? "0" : res;
25     }

 

Leetcode#43 Multiply Strings

标签:

原文地址:http://www.cnblogs.com/boring09/p/4251802.html

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