友情支持
如果您觉得这个笔记对您有所帮助,看在D瓜哥码这么多字的辛苦上,请友情支持一下,D瓜哥感激不尽,😜
有些打赏的朋友希望可以加个好友,欢迎关注D 瓜哥的微信公众号,这样就可以通过公众号的回复直接给我发信息。
公众号的微信号是: jikerizhi 。因为众所周知的原因,有时图片加载不出来。 如果图片加载不出来可以直接通过搜索微信号来查找我的公众号。 |
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 = "2", num2 = "3" Output: "6"
Input: num1 = "123", num2 = "456" Output: "56088"
Note:
-
The length of both
num1
andnum2
is < 110. -
Both
num1
andnum2
contain only digits 0-9. -
Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. -
You must not use any built-in
BigInteger
library or convert the inputs to integer directly.
参考资料
-
优化版竖式(打败99.4%) - 字符串相乘 - 力扣(LeetCode) — 第二种解法,最初没看明白,但是受他们的启发,我自己想到了。
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:
-
The length of both
num1
andnum2
is < 110. -
Both
num1
andnum2
contain only digits0-9
. -
Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. -
You must not use any built-in BigInteger library or convert the inputs to integer directly.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Runtime: 5 ms, faster than 59.85% of Java online submissions for Multiply Strings.
* Memory Usage: 38.5 MB, less than 16.67% of Java online submissions for Multiply Strings.
*/
public String multiply(String num1, String num2) {
if ("0".equals(num1) || "0".equals(num2)) {
return "0";
}
int[] products = new int[num1.length() + num2.length()];
for (int i = num1.length() - 1; i >= 0; i--) {
int iNum = num1.charAt(i) - '0';
if (iNum == 0) {
continue;
}
for (int j = num2.length() - 1; j >= 0; j--) {
int jNum = num2.charAt(j) - '0';
int sum = products[i + j + 1] + iNum * jNum;
products[i + j + 1] = sum % 10;
products[i + j] += sum / 10;
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < products.length; i++) {
if (i == 0 && products[i] == 0) {
continue;
}
sb.append(products[i]);
}
return sb.toString();
}