[Link] https://leetcode.com/problems/divide-two-integers/
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
class Solution {
public int divide(int dividend, int divisor) {
long quotient = 0, temp = 0, dividendL, divisorL;
int cnt = 0, mask = 1, sign = 1;
mask <<= 31;
if((dividend & mask) != 0) {
sign *= -1;
dividendL = (long)(dividend ^ (-1)) + 1;
} else dividendL = (long)dividend;
if((divisor & mask) != 0) {
sign *= -1;
divisorL = (long)(divisor ^ (-1)) + 1;
} else divisorL = (long)divisor;
while(dividendL >= divisorL) {
temp = divisorL;
cnt = 0;
while(temp <= dividendL) {
temp <<= 1;
cnt++;
}
temp >>= 1;
cnt--;
dividendL -= temp;
quotient += (long)1 << cnt;
}
long ans = quotient * sign;
if(Integer.MAX_VALUE < ans) return Integer.MAX_VALUE;
if(Integer.MIN_VALUE > ans) return Integer.MIN_VALUE;
return (int)ans;
}
}