Skip to content

Commit 258a5c1

Browse files
refactor 29
1 parent 546b316 commit 258a5c1

File tree

1 file changed

+43
-39
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+43
-39
lines changed
Lines changed: 43 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,54 @@
11
package com.fishercoder.solutions;
22

33
/**
4+
* 29. Divide Two Integers
5+
*
46
* Divide two integers without using multiplication, division and mod operator.
5-
6-
If it is overflow, return MAX_INT.
7+
* If it is overflow, return MAX_INT.
78
*/
89
public class _29 {
910

11+
public static class Solution1 {
1012
public int divide(int dividend, int divisor) {
11-
if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) {
12-
return Integer.MAX_VALUE;
13-
}
14-
if (dividend != Integer.MIN_VALUE
15-
&& Math.abs(dividend) < Math.abs(divisor)) {
16-
return 0;
17-
}
18-
if (divisor == Integer.MIN_VALUE) {
19-
return (dividend == Integer.MIN_VALUE) ? 1 : 0;
20-
}
21-
//
22-
boolean flag = (dividend < 0) ^ (divisor < 0);
23-
dividend = -Math.abs(dividend);
24-
divisor = -Math.abs(divisor);
25-
int[] num = new int[40];
26-
int[] multiple = new int[40];
27-
num[1] = divisor;
28-
multiple[1] = 1;
29-
for (int i = 2; i < 32 && num[i - 1] < 0; ++i) {
30-
num[i] = num[i - 1] << 1;
31-
System.out.print("num[" + i + "]:" + num[i]);
32-
multiple[i] = multiple[i - 1] << 1;
33-
System.out.println("\tmultiple[" + i + "]" + multiple[i]);
34-
}
35-
int result = 0;
36-
int index = 1;
37-
while (num[index] < 0) {
38-
++index;
39-
}
40-
index -= 1;
41-
while (dividend <= divisor) {
42-
while (dividend <= num[index]) {
43-
result += multiple[index];
44-
dividend -= num[index];
45-
}
46-
--index;
13+
if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) {
14+
return Integer.MAX_VALUE;
15+
}
16+
if (dividend != Integer.MIN_VALUE
17+
&& Math.abs(dividend) < Math.abs(divisor)) {
18+
return 0;
19+
}
20+
if (divisor == Integer.MIN_VALUE) {
21+
return (dividend == Integer.MIN_VALUE) ? 1 : 0;
22+
}
23+
24+
boolean flag = (dividend < 0) ^ (divisor < 0);
25+
dividend = -Math.abs(dividend);
26+
divisor = -Math.abs(divisor);
27+
int[] num = new int[40];
28+
int[] multiple = new int[40];
29+
num[1] = divisor;
30+
multiple[1] = 1;
31+
32+
for (int i = 2; i < 32 && num[i - 1] < 0; ++i) {
33+
num[i] = num[i - 1] << 1;
34+
multiple[i] = multiple[i - 1] << 1;
35+
}
36+
37+
int result = 0;
38+
int index = 1;
39+
while (num[index] < 0) {
40+
++index;
41+
}
42+
index -= 1;
43+
44+
while (dividend <= divisor) {
45+
while (dividend <= num[index]) {
46+
result += multiple[index];
47+
dividend -= num[index];
4748
}
48-
return !flag ? result : -result;
49+
--index;
50+
}
51+
return !flag ? result : -result;
4952
}
53+
}
5054
}

0 commit comments

Comments
 (0)