leetcode 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.

Example 1:

Input: num1 = "2", num2 = "3"
Output: "6"

Example 2:

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

Note:

  1. The length of both num1 and num2 is < 110.
  2. Both num1 and num2 contain only digits 0-9.
  3. Both num1 and num2 do not contain any leading zero, except the number 0 itself.
  4. You must not use any built-in BigInteger library or convert the inputs to integer directly.

 

题目大意:两个非负整数用字符串表示,返回两个数的乘积,也表示为字符串。

注意:两个数的长度不超过100, 两个数只包含0-9的数,两个数没有前导0, 除了0本身。

不能使用内置的大整数库,或者直接将输入转为整数。

 

题目分析:模拟小学数乘。

数num1的长度len1, num2的长度为len2, 乘法结果长度最多为len1 + len2.

 

 我们只要计算最终位置的每个值即可,如例子所示。num1 = "123", num2 = "456", 我们开辟一个长为6的字符串,

index[5] = (num1[2] * num2[2] + 0(由于刚开始乘,进位为0)= 18) % 10 = 8,           flag = 18 / 10 = 1 (进位)

index[4] = ((num1[1] * num2[2] + num1[2] * num2[1] + 1) = 2 x 6 + 3 x 5 + 1 = 28) % 10 = 8,            flag = 28 / 10 = 2

index[3] = ((num1[0] * num2[2] + num1[1] * num2[1] + num1[2] * num2[0] + 2) = 1 x 6 + 2 x 5 + 3 x 4 + 2 = 30) % 10 = 0,           flag = 30 / 10 = 3

index[2] = ((num1[0] * num2[1] + num1[1] * num2[0] + 3) = (1 x 5 + 2 x 4 + 3) = 16) % 10 = 6,        flag = 16 /10 = 1

index[1] = ((num1[0] * num2[0] + 1) = 1 x 4 + 1 = 5,            flag = 5 / 10 = 0

index[0] = 0.

得到字符串:056088

我们需要去掉前导0,返回结果。

 1 string multiply(string num1, string num2) {
 2         int len1 = num1.length(), len2 = num2.length();
 3         string s(len1 + len2, '0');
 4         int sum = 0, flag = 0, up;
 5         for (int i = len1 + len2 - 1; i >= 0; --i) {
 6             sum = flag;
 7             for (int j = len2 - 1; j >= 0; --j) {
 8                 if (i - 1 >= j && (i - 1 - j < len1)) {
 9                     sum += (num2[j] - '0') * (num1[i - 1 - j] - '0');
10                 }
11             }
12             flag = sum / 10;
13             s[i] = '0' + sum % 10;
14         }
15         for (int i = 0; i < len1 + len2; ++i) {
16             if (s[i] != '0')
17                 return s.substr(i);
18         }
19         return "0";
20     }

 

posted @ 2019-11-19 15:01  琴影  阅读(156)  评论(0编辑  收藏  举报