描述
將兩個整數(shù)相除空执,要求不使用乘法、除法和 mod 運算符穗椅。
如果溢出辨绊,返回 2147483647 。
樣例
給定被除數(shù) = 100 匹表,除數(shù) = 9门坷,返回 11。
代碼
public class Solution {
/**
* @param dividend the dividend
* @param divisor the divisor
* @return the result
*/
public int divide(int dividend, int divisor) {
if (divisor == 0) {
return dividend >= 0? Integer.MAX_VALUE : Integer.MIN_VALUE;
}
if (dividend == 0) {
return 0;
}
if (dividend == Integer.MIN_VALUE && divisor == -1) {
return Integer.MAX_VALUE;
}
boolean isNegative = (dividend < 0 && divisor > 0) ||
(dividend > 0 && divisor < 0);
long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);
int result = 0;
while(a >= b){
int shift = 0;
while(a >= (b << shift)){
shift++;
}
a -= b << (shift - 1);
result += 1 << (shift - 1);
}
return isNegative? -result: result;
}
}