forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
34 lines (32 loc) · 861 Bytes
/
Solution.java
File metadata and controls
34 lines (32 loc) · 861 Bytes
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
public class Solution {
public int divide(int a, int b) {
if (b == 0) return Integer.MAX_VALUE;
int result = 0;
if (a == Integer.MIN_VALUE) {
result = 1;
a += Math.abs(b);
}
if (b == Integer.MIN_VALUE) return result;
boolean isNegative = (a < 0) ^ (b < 0);
a = Math.abs(a);
b = Math.abs(b);
int digit = 0;
while (b <= (a >> 1)) {
b <<= 1;
digit++;
}
while (digit >= 0) {
if (a >= b) {
a -= b;
result += 1 << digit;
}
b >>= 1;
digit--;
}
return isNegative ? -result : result;
}
public static void main(String[] args) {
Solution s = new Solution();
System.out.println(s.divide(12, 3));
}
}