Skip to content

Commit b2736dd

Browse files
authored
Merge pull request neetcode-gh#497 from vorenusCoA/main
Adding java solution for 43-Multiply-Strings
2 parents 7f9b7c3 + 521a59b commit b2736dd

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

java/43-Multiply-Strings.java

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Solution {
2+
public String multiply(String num1, String num2) {
3+
4+
if ("0".equals(num1) || "0".equals(num2)) {
5+
return "0";
6+
}
7+
8+
int[] res = new int[num1.length() + num2.length()];
9+
10+
num1 = reverseString(num1);
11+
num2 = reverseString(num2);
12+
13+
for (int i = 0; i < num1.length(); i++) {
14+
for (int j = 0; j < num2.length(); j++) {
15+
int digit = Integer.valueOf(String.valueOf(num1.charAt(i))) * Integer.valueOf(String.valueOf(num2.charAt(j)));
16+
res[i + j] += digit;
17+
res[i + j + 1] += res[i + j] / 10;
18+
res[i + j] = res[i + j] % 10;
19+
}
20+
}
21+
22+
reverseArrayInPlace(res);
23+
24+
// Get the proper starting point to avoid leading zeros
25+
int startIndex = 0;
26+
while (startIndex < res.length) {
27+
if (res[startIndex] != 0) {
28+
break;
29+
}
30+
startIndex++;
31+
}
32+
33+
StringBuilder buildResponse = new StringBuilder();
34+
for (int i = startIndex; i < res.length; i++) {
35+
buildResponse.append(res[i]);
36+
}
37+
38+
return buildResponse.toString();
39+
}
40+
41+
private String reverseString(String str) {
42+
StringBuilder reversedStr = new StringBuilder(str);
43+
reversedStr.reverse();
44+
return reversedStr.toString();
45+
}
46+
47+
private void reverseArrayInPlace(int[] arr) {
48+
for (int i = 0; i < arr.length / 2; i++) {
49+
int temp = arr[i];
50+
arr[i] = arr[arr.length - i - 1];
51+
arr[arr.length - i - 1] = temp;
52+
}
53+
}
54+
55+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy