Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
題意:不使用乘,除,模符號作除法運算
解決思路:每一個數都可以用2進制表示,利用這一點通過位運算完成
代碼:
public class Solution {
public int divide(int dividend, int divisor) {
if(divisor == 0){
return Integer.MAX_VALUE;
}else if(divisor == 1){
return dividend;
}else if(divisor == -1){
return dividend == Integer.MIN_VALUE ? Integer.MAX_VALUE : -dividend;
}else{
final int sign = ((dividend > 0 && divisor < 0) || (dividend < 0 && divisor > 0))? -1 : 1;
long lDividend = Math.abs((long)dividend);
long lDivisor = Math.abs((long)divisor);
int result = 0;
for(int i = Integer.SIZE - 1; i >= 0 && lDividend >= lDivisor; i--){
if(lDividend >= (lDivisor << i)){
lDividend -= lDivisor << i;
result |= 1 << i;
}
}
return result * sign;
}
}
}