LeetCode 43 - 大数乘法

模拟算乘法,实现大整数乘法。仅限整数,负数要加点判断条件。

这个方法虽然不是最快的,但比较好理解。

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution {
public String multiply(String num1, String num2) {
// trivial case
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
if (num1.equals("1"))
return num2;
if (num2.equals("1"))
return num1;

// method call optimition
int len1 = num1.length();
int len2 = num2.length();

// target result;
int[] res = new int[len1 + len2];

for (int i = len1 - 1; i >= 0; i--) {
for (int j = len2 - 1; j >= 0; j--) {
// multiply single numbers
int tmp = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
// len - i - 1 means indentation
// add up two single num
res[(len1 - i - 1) + len2 - j - 1] += tmp % 10;

// carry
int add = res[(len1 - i - 1) + len2 - j - 1] / 10;
res[(len1 - i - 1) + len2 - j - 1] %= 10;
res[(len1 - i - 1) + len2 - j] += add;
res[(len1 - i - 1) + len2 - j] += tmp / 10;
}
}
int fin = res.length - 1;
while (res[fin] == 0)
fin--;
StringBuilder sb = new StringBuilder();
// reverse order to append as string
while (fin >= 0) {
sb.append((char) (res[fin--] + '0'));
}
return sb.toString();
}
}

评论

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×