-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiply Strings
More file actions
46 lines (30 loc) · 1.01 KB
/
Copy pathMultiply Strings
File metadata and controls
46 lines (30 loc) · 1.01 KB
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
LLETCODE PROBLEM SOLVING
PROBLEM->MULTIPLY STRINGS
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0"))
return "0";
int n = num1.length();
int m = num2.length();
int[] result = new int[n + m];
for (int i = n - 1; i >= 0; i--) {
for (int j = m - 1; j >= 0; j--) {
int digit1 = num1.charAt(i) - '0';
int digit2 = num2.charAt(j) - '0';
int product = digit1 * digit2;
int pos1 = i + j;
int pos2 = i + j + 1;
int sum = product + result[pos2];
result[pos2] = sum % 10;
result[pos1] += sum / 10;
}
}
StringBuilder answer = new StringBuilder();
for (int digit : result) {
if (answer.length() == 0 && digit == 0)
continue;
answer.append(digit);
}
return answer.toString();
}
}