43. Multiply Strings

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 };

猜你喜欢

转载自www.cnblogs.com/Zzz-y/p/9009913.html
今日推荐