Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路1:看样只能用减法了,依次减去除数,TOTS,肯定超时。
思路2:每次减去N倍的除数,结果也加上N次,因此我们需要将除数扩大N倍。
代码如下:
public int divide(int dividend, int divisor) { if (dividend == 0 || divisor == 1) return dividend; long divid = dividend; long divis = divisor; boolean neg = false; int result = 0; if (dividend < 0) { neg = !neg; divid = -divid; } if (divisor < 0) { neg = !neg; divis = -divis; } long[] multi = new long[32]; for (int i = 0; i < 32; i++) multi[i] = divis << i; for (int i = 31; i >= 0; i--) { if (divid >= multi[i]) { result += 1 << i; divid -= multi[i]; } } if(result==Integer.MIN_VALUE)return Integer.MAX_VALUE; return (neg ? -1 : 1) * result; }
原文地址:http://blog.csdn.net/u012734829/article/details/44080991