题目如下:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
分析:
整型相除,不使用乘除法的话,只能使用减法较为简单了。即循环使用被减数去减减数。但如果被减数很大,减数很小,则循环次数太大,效率过低。因此可以对减数进行放大,以逼近被减数。放大倍数设为2,即左移位操作。
注意:移位前先将整型转为long类型,否则移位可能溢出。
代码如下:
package T029; public class DivideTwoIntegers { public static void main(String[] args) { //divide(-2147483648,-1) System.out.println(divide(-2147483648,-2)); } public static int divide(int dividend, int divisor) { long isNegative = (dividend < 0 && divisor > 0) || (dividend > 0 && divisor < 0) ? -1 : 1; long absDividend = Math.abs((long) dividend); long absDivisor = Math.abs((long) divisor); long result = 0; while(absDividend >= absDivisor){ long tmp = absDivisor, count = 1; while(tmp <= absDividend){ tmp <<= 1; count <<= 1; } result += count >> 1; absDividend -= tmp >> 1; } result = result*isNegative; if(result>Integer.MAX_VALUE || result <Integer.MIN_VALUE) return Integer.MAX_VALUE; return (int) result; } }