Divide Two Integers
Divide Two Integers
问题:
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
思路:
二分查找
系统解法:https://blog.csdn.net/whuwangyi/article/details/40995863
我的代码:
public class Solution { public int divide(int dividend, int divisor) { if(divisor == 0) return Integer.MAX_VALUE; if(dividend == 0) return 0; boolean flag = true; if((dividend < 0 && divisor > 0)||(dividend > 0 && divisor < 0)) { flag = false; } long top = Math.abs((long)dividend); long down = Math.abs((long)divisor); long[] rst = helper(top, down); long result = (flag ? rst[0] : -rst[0]); if(result > Integer.MAX_VALUE || result < Integer.MIN_VALUE) return Integer.MAX_VALUE; return (int)result ; } public long[] helper(long dividend, long divisor) { long[] rst = new long[2]; if(dividend == divisor) { rst[0] = 1; rst[1] = 0; return rst; } if(dividend < divisor) { rst[0] = 0; rst[1] = dividend; return rst; } long mid = dividend >> 1; rst = helper(mid, divisor); long remain = dividend - (mid << 1) + (rst[1] <<1); if(remain >= divisor) { rst[0] = (rst[0]<<1) + 1; rst[1] = remain - divisor; } else { rst[0] = (rst[0]<<1); rst[1] = remain; } return rst; } }
他人代码:
public int divide(int dividend, int divisor) { long a = Math.abs((long)dividend); long b = Math.abs((long)divisor); long ret = 0; while (a >= b) { for (long tmp = b, cnt = 1; a >= tmp; tmp <<= 1, cnt <<= 1) { ret += cnt; a -= tmp; } } ret = (((dividend ^ divisor) >> 31) & 1) == 1 ? -ret: ret; if (ret > Integer.MAX_VALUE || ret < Integer.MIN_VALUE) { return Integer.MAX_VALUE; } return (int)ret; }
学习之处:
- 判断两个数相乘是否为负数, ret = (((dividend ^ divisor) >> 31) & 1) == 1 ? -ret: ret; 这个方法真简洁
- 我的代码太过于臃肿,看看别人的代码是如此的简介,我的代码可取之处只是思路更加清晰一点而已
- 既然不能用乘除法,还可以用移位操作嘛
posted on 2015-04-02 10:58 zhouzhou0615 阅读(146) 评论(0) 编辑 收藏 举报