LeetCode


题目:

Divide two integers without using multiplication, division and mod operator.

If it is overflow, return MAX_INT.

思路:

吐槽这种题目,这就像你明明可以买到过年回家的直达票,有票且一键解决,却去买分段票,路途不耽误时间吗?而且买分段票时中间容易出差错(bugs),最终可能回不了家(运行结果错误)。

package manipulation;

public class DivideTwoIntegers {

public int divide(int dividend, int divisor) {
if ((dividend == Integer.MIN_VALUE && divisor == -1) || divisor == 0) return Integer.MAX_VALUE;
if (divisor == 1) return dividend;
if (divisor == -1) return -dividend;

long a = Math.abs((long)dividend);
long b = Math.abs((long)divisor);

long base = b;
int i = 0;
long[] nums = new long[32];
nums[
0] = b;
while (nums[i] <= a && nums[i] > 0) {
nums[i
+1] = base << (i+1);
++i;
}
--i;

int cnt = 0;
while (a > 0 && i >= 0) {
while (a - nums[i] >= 0) {
a
-= nums[i];
cnt
+= (1 << i);
}
--i;
}

return ((dividend ^ divisor) >> 31) == 0 ? cnt : -cnt;
}

public static void main(String[] args) {
// TODO Auto-generated method stub
DivideTwoIntegers d = new DivideTwoIntegers();
System.out.println(d.divide(
-2147483648, 2));
}

}

 

本站声明
本文转载自:http://www.cnblogs.com/shuaiwhu/p/5065437.html     作者:Divide Two Integers - NULL00     发布日期:2015/12/22     本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。


 
© 2014-2017 ITdaan.com 粤ICP备14056181号