Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Subscribe to see which companies asked this question
让除数大于被除数右移一位,进行操作:
public class Solution {
public int divide(int dividend, int divisor) {
int a = dividend, b = divisor;
if(dividend == 0)
return 0;
if(divisor == 1)
return dividend;
if(divisor == -1){
if(dividend == Integer.MIN_VALUE){
return Integer.MAX_VALUE;
}else{
return -dividend;
}
}
int nums = 0, result = 0;
long dividendl = Math.abs((long)dividend);
long divisorl = Math.abs((long)divisor);
while(divisorl <= (dividendl >> 1)){
divisorl <<= 1;
nums++;
}
while(nums >= 0){
if(dividendl >= divisorl){
dividendl -= divisorl;
result += (1 << nums);
}
dividendl <<= 1;
nums--;
}
return ((a ^ b) >>> 31) == 1 ? -result : result;
}
}