-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStringMultiplication.java
More file actions
46 lines (32 loc) · 1.13 KB
/
StringMultiplication.java
File metadata and controls
46 lines (32 loc) · 1.13 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
public class StringMultiplication {
public static 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];
// Multiply from right to left
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;
}
}
// Convert result array to string
StringBuilder sb = new StringBuilder();
for (int num : result) {
if (!(sb.length() == 0 && num == 0)) {
sb.append(num);
}
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(multiply("123", "456")); // 56088
}
}