LeettCode 29. Divide Two Integers
来源:互联网 发布:手机频率对讲机软件 编辑:程序博客网 时间:2024/06/06 04:21
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
求两个整数相除的结果,不允许用到乘、除、求余操作。
最简单的当然是以除数一个一个的加,知道最终超过哟被除数,这样做的话会超时。
代码如下:
int divide(int dividend, int divisor){ if(divisor == 0 || dividend == 0) return 0; dividend = abs(dividend); divisor = abs(divisor); if(dividend < divisor) return 0; else { int ans = 1; int sum = divisor + divisor; while(sum < dividend) { ans++; sum = sum + divisor; } return ans; }}开始的时候我采用的加法思想,上述代码提交的时候超时了,当然上述代码还有结果的符号、溢出的问题没考虑,由于此种思路会超时,所以这些错我我没有去一一解决。
为了降低复杂度,参考网上的解决办法是,每次将除数增加一倍,同时count增加一倍,日过超过了被除数,则用被除数减去当前的和再继续本次操作。
确定了思想之后,主要要解决的就是溢出问题了,主要考虑的是输入的除数或被除数含有-2147483648(0x7fffffff + 1 = 2147483648),若是负数,则最小负数为-2147483648,当-2147483648用abs转换为正整数的时候会出现正溢出。为了解决这个问题,首先需要定义两个long long型的整数来保存除数与被除数。其次,当最终除得的结果为2147483648,由于函数的返回类型为int,次返回结果也会溢出,而题目也已经说明,若最终除得的结果溢出,则返回max_int,即0x7fffffff.
最终AC的代码如下:
int divide(int dividend, int divisor){ //判断最终结果的符号 int flag = 1; if((dividend < 0 && divisor >0) || (dividend > 0 && divisor < 0)) flag = -1; //为防止溢出,定义两个长整形保存输入的除数和被除数 long long a = dividend; long long b = divisor; long long c = abs(a); long long d = abs(b); if((c < d) || c == 0 || d == 0) return 0; else { int ans = 0; while(c >= d) { long long count = 1; long long sum = d; while((sum + sum) <= c) { sum = sum << 1; count = count << 1; } c = c - sum; ans = ans + count; } if(flag > 0 ) { if(ans == 0x7fffffff + 1) ans = 0x7fffffff; return ans; } else return -ans; }}
0 0
- LeettCode 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
- Spring 对hibernate事务处理的实现过程(1) hibernate 自己是怎么做的
- Android中压缩图片的几种方法
- LeetCode 260 Single Number III
- 我的“VLC for Android” 编译之旅
- python错误汇总3:安装MySQLdb时:EnvironmentError: mysql_config not found
- LeettCode 29. Divide Two Integers
- DICOM-RT:放疗流程与参与角色
- 简单说说TCP(5) --- RST
- 往Oracle数据库中插入日期型数据(to_date的用法)
- java注解
- jvm----GC回收机制
- [MySQL]Mysql常用命令-20160410
- OD快捷键使用大全。非常详细(游戏逆向分析必看)
- 最近改完的富文本编辑器