This topic has not been done since there are too many corner case to consider.
1. Divisor equals 0.
2. Dividend equals 0.
3. Is the result negative?
4. When dividend equals Integer.min_value and divisor equals-1, the result would overflow. Convert result to long and then to Integer.
5. Divided by divisor * 2 ^ n to avoid exceeding time limit
6. There is a to convert divisor and dividend to a long to avoid overflow in shift.
7. Constant 1 in Java are compiled as Integer by default.
Public classSolution { Public intDivideintDividend,intdivisor) { if(Divisor = = 0) { returnDividend >= 0?Integer.MAX_VALUE:Integer.MIN_VALUE; } if(Dividend = = 0) { return0; } Booleanisnegative = (Dividend > 0 && divisor < 0) | | (Dividend < 0 && divisor > 0); Longx = Math.Abs ((Long) dividend); Longy = Math.Abs ((Long) divisor); Longresult = 0; while(x >=y) {intA = 0; while(x >= (y <<a)) {a++; } A--; Result+= (Long) 1 <<A; X-= y <<A; } if(Result = = (Long) Integer.max_value + 1) { returnIsnegative?Integer.MIN_VALUE:Integer.MAX_VALUE; } returnIsnegative? -(int) Result: (int) result; }}
[Leetcode] 29. Divide integers