refer: https://leetcode.com/problems/divide-two-integers/
package LeetCode;
public class Test {
public static void main(String[] args) {
System.out.println(Integer.MIN_VALUE >> 1);
System.out.println(Integer.MIN_VALUE);
}
// 位运算 + 递归实现
// 思路 : 所有的数字都可以用二进制来表示
/* 计算过程如下
* 100/2 = 2*32 + 2*16 + 2*2;
* 32+16+2 = 50
* 100/3 = 3*32 + 3*1
* 32 + 1 = 33
*/
public int divide(int dividend, int divisor) {
if (dividend == Integer.MIN_VALUE && divisor == -1)
return Integer.MAX_VALUE;
int positiveDividend = dividend > 0 ? -dividend : dividend;
int positiveDivisor = divisor > 0 ? -divisor : divisor;
int leftTime = 0;
int result = 0;
int maxRight1 = Integer.MIN_VALUE >> 1;
if (dividend == 0 || positiveDividend - positiveDivisor > 0)
return 0;
while (positiveDividend - positiveDivisor < 0) {
if (positiveDivisor < maxRight1 || positiveDividend - (positiveDivisor << 1) > 0) break;
positiveDivisor = positiveDivisor << 1;
leftTime ++;
}
// 递归
result = (1 << leftTime)
+ divide(positiveDividend - positiveDivisor, divisor > 0 ? 0 - divisor : divisor);
if ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0)) {
result = 0 - result;
}
return result;
}
}