29. Divide Two Integers
来源:互联网 发布:uber隐瞒数据泄露事件 编辑:程序博客网 时间:2024/05/16 09:46
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
Subscribe to see which companies asked this question
不用乘除法和取模运算计算除法。
超范围的情况
1.除数为0
2.被除数为Integer.MIN_VALUE 除数为-1 这样结果会是Integer.MAX_VALUE+1 因为负数最小值能比正数最大值多1
剩余就是全转成正数,然后用二进制除法算就好
public class Solution { public int divide(int dividend, int divisor) { if(dividend==-2147483648&&divisor==-1)return Integer.MAX_VALUE; if(divisor==0)return Integer.MAX_VALUE ; int flag = 1; if(dividend<0)flag=-flag; if(divisor<0)flag = -flag; long dia =Math.abs((long)dividend); long dib =Math.abs((long)divisor); long c = 1; while(dia > dib){ dib = dib << 1 ; c = c << 1; } int res = 0; while (dia>=Math.abs((long)divisor)){ while(dia>=dib){ dia = dia - dib; res+=c; } dib=dib>>1; c=c>>1; }if(flag>0)return (int)res; else return (int)(-res); } }
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
- 面向切面(AOP)之Spring接口方式 schema配置方式 aspectj注解方式
- 151. Reverse Words in a String
- [Unity3d]打包Assetbundle并加载
- Go语言核心之美 2.6-常量
- 通过resize事件,判断当前浏览设备
- 29. Divide Two Integers
- iOS开发:正确使用const,static,extern
- vim 注释方法
- 使用JDBC中PreparedStatement时,sql语句中中文出现问号
- Android 中Base64编码解码
- 剑指offer面试题之变态跳台阶
- 166. Fraction to Recurring Decimal
- eclipse从数据库获取数据时控制台乱码问题
- EventBus3.0性能优化之添加索引(Index)