Divide two integers
来源:互联网 发布:嵌入式linux系统下载 编辑:程序博客网 时间:2024/06/03 15:13
尼玛考虑负数的情况!而且还有溢出的情况。。。。 -(-2147483648)溢出啦 亲。。。
bit operator的妙用, 左移实现乘2功能
public class Solution { public int divide(int dividend, int divisor) { long a = Math.abs((long)dividend); long b = Math.abs((long)divisor); boolean pos = false; if (dividend > 0 && divisor > 0 || dividend < 0 && divisor < 0) { pos = true; } int ans = 0; while (a >= b) { int shift = 0; while ( (b << shift) <= a) { shift++; } ans += (1 << (shift - 1)); a -= (b << (shift - 1)); } return pos? ans : -ans; }}
如果允许乘法,试着用binary search做了下
//注意dividend是0的情况,这个时候sum总是比被除数大的!//尼玛考虑负数的情况!而且还有溢出的情况。。。。 -(-2147483648)溢出啦 亲。。。//要从O(n) -> O(lgn) -> O(1)public class Solution { public int divide(int dividend, int divisor) { long a = Math.abs((long)dividend); long b = Math.abs((long)divisor); boolean pos = false; if (dividend > 0 && divisor > 0 || dividend < 0 && divisor < 0) { pos = true; } int ans = 0; long beg = 1; long end = a; while (beg <= end) { long mid = (beg + end)/2; if (b * mid <= a && b * (mid + 1) > a) { ans = (int)mid; break; } if (b * (mid + 1) <= a) { beg = mid + 1; } else { end = mid - 1; } } return pos? ans : -ans; }}
0 0
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- Divide Two Integers
- Divide Two Integers
- LeetCode28:Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode Divide Two Integers
- Divide Two Integers
- 【leetcode】Divide Two Integers
- Divide Two Integers
- Divide Two Integers
- [LeetCode]Divide Two Integers
- Divide Two Integers
- LeetCode-Divide Two Integers
- Divide Two Integers
- 25 - Divide Two Integers
- 严格模式与混杂模式——如何触发这两种模式,区分它们有何意义
- 火狐网址
- c# winform 遍历TreeView控件(属性为checkbox时)中,所有被选中的节点
- Android的AlertDialog详解
- 产品设计必读书籍推荐
- Divide two integers
- Android调用asp.net编写的*.ashx(一般处理程序)获取数据
- Hyper-v不能启动与开机BCD启动菜单有关!恢复BCD问题解决
- 异常处理系列: android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
- 你确定,这个平台已经死亡了,啊?
- 旋转列表
- Spring注解详解
- 命名空间System.Configuration中不存在类型或命名空间名称ConfigurationManager
- 海钻装饰材料有限公司 冰花玉石背景墙 玉石透光板 玉石线条 产品相册