-
Notifications
You must be signed in to change notification settings - Fork 53
Expand file tree
/
Copy path43. Multiply Strings
More file actions
37 lines (36 loc) · 1.39 KB
/
43. Multiply Strings
File metadata and controls
37 lines (36 loc) · 1.39 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
class Solution {
public String multiply(String num1, String num2) {
if(num1 == null || num2 == null){
return null;
}
if(num1.charAt(0) == '0' || num2.charAt(0) == '0'){
return "0";
}
int[] retval = new int[num1.length() + num2.length()];
StringBuilder builder = new StringBuilder();
int extraValue = 0;
for(int i = num1.length() - 1; i >= 0; i--){
for(int j = num2.length() - 1; j >= 0; j--){
//Find total of two numbers
int total = (Character.getNumericValue(num1.charAt(i))) * (Character.getNumericValue(num2.charAt(j))) + extraValue;
//Figure out where to insert and insert it
int spotToInsertValue = retval.length - ((num1.length() - i) + (num2.length() - j)) + 1;
retval[spotToInsertValue] += total;
}
}
for(int i = retval.length - 1; i >= 0; i--){
retval[i] += extraValue;
extraValue = retval[i] / 10;
retval[i] = retval[i] % 10;
}
for(int i = 0; i < retval.length; i++){
if(retval[i] != 0){
for(int j = i; j < retval.length; j++){
builder.append((char)(retval[j] + 48));
}
break;
}
}
return builder.toString();
}
}