LeetCode 算法题解与代码实现

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
class Solution {
public String multiply(String num1, String num2) {
if (num1.charAt(0) == '0' || num2.charAt(0) == '0')
return "0";

String ans = "0";
for (int i = num2.length() - 1; i >= 0; i--) {
StringBuilder sb = new StringBuilder();
int y = num2.charAt(i) - '0';
int cin = 0;
for (int j = num1.length() - 1; j >= 0; j--) {
int x = num1.charAt(j) - '0';
int product = x * y + cin;
cin = 0;
if (product >= 10) {
cin = product / 10;
product = product % 10;
}
sb.append(product);
}
if (cin != 0) {
sb.append(cin);
}
sb.reverse();
for (int j = 0; j < num2.length() - 1 - i; j++) {
sb.append(0);
}

ans = add(ans, sb.toString());
}
return ans;
}


public String add(String num1, String num2) {
int cin = 0;
int i = num1.length() - 1, j = num2.length() - 1;
StringBuilder sb = new StringBuilder();
while (i >= 0 || j >= 0 || cin == 1) {
int n1 = 0, n2 = 0;
if (i >= 0) {
n1 = num1.charAt(i) - '0';
i--;
}
if (j >= 0) {
n2 = num2.charAt(j) - '0';
j--;
}
int sum = n1 + n2 + cin;
cin = 0;
if (sum >= 10) {
cin = 1;
sum -= 10;
}
sb.append(sum);
}
return sb.reverse().toString();
}
}

Comments
Recent Posts
Untitled
Categories
Tags
Website Info
Article Count :
2
Total Word Count :
1.6k
Unique Visitors :
Page Views :
Last Update :