29. Divide Two Integers
来源:互联网 发布:html与css javascript 编辑:程序博客网 时间:2024/05/17 19:55
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
实现两个数相除,但不能使用除号和取模符号,很明显,本题基本上是用加、减、移位运算来实现除法运算。用减法就可以实现除法运算,一直减去被除数,最后得到除法运算的值,但这种方法会TimeOut,因为当除数为Integer.MAX_VALUE,被除数为1时,会计算Integer.MAX_VALUE次,效率很低。
另一种效率较高的方法:
a/b = a0*2^0 + a1*2^1 + ... + ai*2^i + an*2^n;其中ai为0或1,通过这种方法,只要确定最大的a_max = max(a0, a1, ... ai)的i值(如程序中的index值),再将a_max前面ai不为0的多项式相加,即为a/b的值。
数值运算一定要注意边界条件,不外乎就整数的上下界拿出来单独考虑,分类并不多。
程序如下:
class Solution { public int divide(int dividend, int divisor) { if(divisor == 0){ return Integer.MAX_VALUE; } if (dividend == Integer.MIN_VALUE){ if (divisor == -1){ return Integer.MAX_VALUE; } } long digit0 = Math.abs((long)dividend); long digit1 = Math.abs((long)divisor); int result = 0, sign = ((((dividend >> 31)&0x1)^((divisor >> 31)&0x1))==1)?-1:1; int index = 0; while (digit1 <= (digit0>>1)){ index ++; digit1 <<= 1; } while (index >= 0){ if (digit0 >= digit1){ result += (1 << index); digit0 = digit0 - digit1; } index--; digit1 >>= 1; } 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
- linux .tar.gz文件 解压缩命令简单使用
- 软件测试面试题
- 面向对象六大设计原则(一)单一职责原则
- Python中列表常用的操作符
- 统计字符串字母,数字,空格和其他字符个数
- 29. Divide Two Integers
- HashMap,HashSet,HashTable,LinkedHashMap,LinkedHashSet,ArrayList,LinkedList,ConcurrentHashMap,Vector
- 【目标检测】RCNN算法详解
- 数据库那些事
- LinearLayout动态添加控件及将某XML动态加入到Activity显示(1)
- centos7.3实现基于源码编译安装LAMP的wordpress应用
- Java练习(4)
- 我的第001天学习记录
- 顺序表