-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathMultiplyStrings.java
More file actions
44 lines (38 loc) · 1.21 KB
/
MultiplyStrings.java
File metadata and controls
44 lines (38 loc) · 1.21 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
package algorithm.lc;
import java.util.Arrays;
/**
* Given two numbers represented as strings, return multiplication of the
* numbers as a string.
*
* Note: The numbers can be arbitrarily large and are non-negative.
*
*/
// O(m+n) space, O(n * n) time
public class MultiplyStrings {
public class Solution {
// start from the highest digit of num1, multiply each digit of num2
public String multiply(String num1, String num2) {
// Start typing your Java solution below
// DO NOT write main() function
int[] res = new int[num1.length() + num2.length()];
for (int i = num2.length() - 1; i >= 0; --i) {
int carry = 0;
for (int j = num1.length() - 1; j >=0; --j) {
int tmp = carry + res[i + j + 1] + (num1.charAt(j) - '0') * (num2.charAt(i) - '0');
res[i + j + 1] = tmp % 10;
carry = tmp / 10;
}
res[i] = carry; // put carry to higher digit
}
int i = 0;
StringBuilder sb = new StringBuilder();
while (i < res.length - 1 && res[i] == 0) { // remove leading 0s
++i;
}
while (i < res.length) {
sb.append(res[i++]);
}
return sb.toString();
}
}
}