-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMultiplyStrings.java
More file actions
103 lines (96 loc) · 2.34 KB
/
MultiplyStrings.java
File metadata and controls
103 lines (96 loc) · 2.34 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package multiplyStrings;
public class MultiplyStrings {
public String multiply(String num1, String num2) {
if(num1.equals("0") || num2.equals("0")){
return "0";
}
String result = "0";
if(num1.length() < num2.length()){
String tmp = null;
tmp = num1;
num1 = num2;
num2 = tmp;
}
for(int i = num2.length()-1; i >= 0; i--){
char rate = num2.charAt(i);
String tmp = multiply(num1, rate, num2.length()-1-i);
result = add(tmp, result);
}
result = rotate(result);
return result;
}
public String multiply(String multi, char rate, int round){
String result = "";
int a = (int)rate - 48;
int front = 0;
for(int i = 0; i < round; i++){
result += "0";
}
for(int i = multi.length()-1; i >= 0; i--){
char mul = multi.charAt(i);
int b = (int)mul - 48;
int middleResult = a*b + front;
int middleString = middleResult%10;
front = middleResult/10;
result += String.valueOf(middleString);
}
if(front != 0){
result += String.valueOf(front);
}
return result;
}
public String add(String add1, String add2){
//×Ö·ûÊÇ·´¹ýÀ´µÄ
if(add2.equals("0")){
return add1;
}
if(add1.equals("0")){
return add2;
}
String result = "";
//the length of add1 >= add2
int front = 0;
for(int i = 0; i < add2.length(); i++){
int a = (int)add2.charAt(i)-48;
int b = (int)add1.charAt(i)-48;
int sum = a+b+front;
if(sum >= 10){
front = 1;
sum = sum - 10;
}
else{
front = 0;
}
result += String.valueOf(sum);
}
if(front == 1){
if(add1.length() - add2.length() == 0){
result += "1";
}
else {
String tmp = add1.substring(add2.length(), add1.length());
String tmpResult = add(tmp, "1");
result += tmpResult;
}
}
else{
result += add1.substring(add2.length(), add1.length());
}
return result;
}
public String rotate(String cur){
char[] tmp = cur.toCharArray();
String result = "";
for(int i = tmp.length-1; i >= 0; i--){
result += tmp[i];
}
return result;
}
public static void main(String[] args){
MultiplyStrings t = new MultiplyStrings();
String a = "4806";
String b = "896";
String result = t.multiply(a, b);
System.out.println(result);
}
}