29. Divide Two Integers
来源:互联网 发布:单倍型分析软件 编辑:程序博客网 时间:2024/06/06 04:14
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
1、让divisor一直乘22、如果divisor>dividend,则用dividend - 上一个divisor
3、余下的数继续重复1,2步
这里有两种情况会溢出:
1、divisor = 0;
2、dividend = INT_MIN && divisor = -1 (因为 abs(INT_MIN) = INT_MAX + 1).
还有一点需要注意temp一直乘2会溢出,用long
dividend,divisor可能是Integer.MIN_VALUE,abs的时候会溢出int,用long缓存一下。abs时需要用java.lang.Math.abs(long a)防止溢出。
代码如下:
public class Solution { public int divide(int dividend, int divisor) { if (divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) { return Integer.MAX_VALUE; } int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; int result = 0; long divd = Math.abs((long)dividend); long div = Math.abs((long)divisor); while (divd >= div) { long mul = 1, temp = div; while (divd >= temp << 1) { temp = temp << 1; mul = mul << 1; } result += mul; divd -= temp; } return sign == -1? -result: result; }}
0 0
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- 29. Divide Two Integers
- [转]多边形点集排序--针对凸多边形,按逆时针方向进行排序
- CELL箭头挡住里底部的线
- Saleforce中的Apex Data Manipulation Language(DML)解析
- 前置变换后置变换OpenCV源代码 转自https://github.com/kipr/opencv/blob/master/modules/legacy/src/lines.cpp
- Field 'New_id' doesn't have a default value
- 29. Divide Two Integers
- WebSocket jfinal 实现简单的聊天室功能
- 设计模式---空对象模式(C++实现)
- android网络访问相关整理
- 设计模式学习笔记——模板(Template)模式
- 性能指标之资源指标-CPU-配置(2)
- weblogic10安装
- 【STL】空间配置器
- 现学现卖微信小程序开发(二)