首页 > 其他 > 详细

43. Multiply Strings

时间:2018-05-08 18:19:25      阅读:199      评论:0      收藏:0      [点我收藏+]

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Input: num1 = "123", num2 = "456"
Output: "56088"

字符串相乘。

解决:

1、n位和m位数字相乘,乘积result不超过m+n位。

2、其中,num1[i] * num2[j] 影响的是 result[i+j+1]

 1 class Solution {
 2 public:
 3     string multiply(string num1, string num2) {
 4         if (num1 == "0" || num2 == "0")
 5             return "0";
 6         int len1 = num1.size();
 7         int len2 = num2.size();
 8         vector<int> v(len1 + len2, 0);
 9         int carry = 0;
10         for (int i=len1-1; i>=0; --i) {
11             carry = 0;
12             for (int j=len2-1; j>=0; --j) {
13                 int n1 = num1[i] - 0;
14                 int n2 = num2[j] - 0;
15                 v[i+j+1] += n1 * n2 + carry;
16                 carry = v[i+j+1] / 10;
17                 v[i+j+1] = v[i+j+1] % 10;
18             }
19             if (carry)
20                 v[i] += carry;
21         }
22         string mul;
23         if (v[0] != 0)
24             mul += v[0] + 0;
25         for (int i=1; i<len1+len2; ++i)
26             mul += v[i] + 0;
27         return mul;
28     }
29 };

 

43. Multiply Strings

原文:https://www.cnblogs.com/Zzz-y/p/9009913.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!