Skip to content

Commit 9697d78

Browse files
authored
Implement string multiplication in Multiply Strings.java
1 parent 10a0de1 commit 9697d78

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

Multiply Strings.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution {
2+
public String multiply(String num1, String num2) {
3+
if ("0".equals(num1) || "0".equals(num2)) {
4+
return "0";
5+
}
6+
int m = num1.length(), n = num2.length();
7+
int[] arr = new int[m + n];
8+
for (int i = m - 1; i >= 0; --i) {
9+
int a = num1.charAt(i) - '0';
10+
for (int j = n - 1; j >= 0; --j) {
11+
int b = num2.charAt(j) - '0';
12+
arr[i + j + 1] += a * b;
13+
}
14+
}
15+
for (int i = arr.length - 1; i > 0; --i) {
16+
arr[i - 1] += arr[i] / 10;
17+
arr[i] %= 10;
18+
}
19+
int i = arr[0] == 0 ? 1 : 0;
20+
StringBuilder ans = new StringBuilder();
21+
for (; i < arr.length; ++i) {
22+
ans.append(arr[i]);
23+
}
24+
return ans.toString();
25+
}
26+
}

0 commit comments

Comments
 (0)