-
Notifications
You must be signed in to change notification settings - Fork 2
/
Divide.java
39 lines (35 loc) · 1.11 KB
/
Divide.java
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
package leetcode.math;
public class Divide {
// Notice: the integer division truncates toward zero.
public int divide(int dividend, int divisor) {
// Handles the special case first.
if (dividend == 0) {
return 0;
} else if (divisor == 1) {
return dividend;
} else if (dividend == Integer.MIN_VALUE) {
if (divisor == -1) {
return Integer.MAX_VALUE;
}else if (divisor < 0) {
return divide(dividend - divisor, divisor) + 1;
} else {
return divide(dividend + divisor, divisor) - 1;
}
}
// Records the supposed sign (positive/negative) of the result.
int sign = 1;
if (dividend > 0 && divisor < 0) {
sign = -1;
} else if (dividend < 0 && divisor > 0) {
sign = -1;
}
int result = 0;
dividend = Math.abs(dividend);
divisor = Math.abs(divisor);
while (dividend >= divisor) {
result++;
dividend -= divisor;
}
return result * sign;
}
}