NOTES ON SOME BIT HACKS:
1. x << n is equivalent to x * Math.pow(2, n). (<< is Leftshift Operator)
2. 1 << x is equivalent to Math.pow(2, x). (<< is Leftshift Operator)
3. x and y have opposite signs if (x ^ y) < 0. (^ is Bitwise XOR)
注意几点,一开始被除数、除数、商全部转化成long. 并且被除数除数都取转化成long之后的绝对值带入计算。需要处理的edge cases只有除数为0,以及被除数为Integer.MIN_VALUE除数为 -1的情况,此时商为Integer.MAX_VALUE. sign都可一开始就求出来。
class Solution {
public int divide(int dividend, int divisor) {
if (divisor == 0){
return Integer.MAX_VALUE;
}
if (dividend == Integer.MIN_VALUE && divisor == -1){
return Integer.MAX_VALUE;
}
int sign = 1;
if (dividend > 0 && divisor < 0 || (dividend < 0 && divisor > 0)){
sign = -1;
}
long lDividend = Math.abs((long) dividend);
long lDivisor = Math.abs((long)divisor);
int powerOfTwo = 0;
long quotient = 0;
while (lDividend >= lDivisor){
powerOfTwo = 0;
while (lDivisor << powerOfTwo <= lDividend){
powerOfTwo++;
}
powerOfTwo = powerOfTwo - 1;
quotient += (1 << powerOfTwo);
lDividend -= (lDivisor << powerOfTwo);
}
return (int) quotient*sign;
}
}
网友评论