29. Divide Two Integers
来源:互联网 发布:趣头条提现是骗局 知乎 编辑:程序博客网 时间:2024/04/30 17:42
1.问题描述
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
2.解题思路采用二分法,每次让除数以2倍的形式递增,只要递增结果小于被除数,则继续递增,如果递增时超过了,则记住递增前的数,然后用被除数减去递增前的数,再次倍数递增,直到被除数的值小于除数
3.代码实现
class Solution {public:long long myAbs(const int x) {if (x > 0)return x;return -(static_cast<long long>(x));}int divide(int dividend, int divisor) {if (divisor == 0||dividend == 0)return 0;long long count = 0;long long tmp = 0;long long absDividend = myAbs(dividend);long long absDivisor = myAbs(divisor);long long sum = absDivisor;while (absDividend >= absDivisor) {tmp = 1;sum = absDivisor;while (sum + sum <= absDividend) {sum += sum;tmp += tmp;}count += tmp;absDividend -= sum;}if (divisor < 0 && dividend>0 || divisor > 0 && dividend < 0)count = -count;if (count > 2147483647)return 2147483647;return count;}};
4.结果截图
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
- POJ 2777 Count Color
- 日期计算
- Codeforces 444C DZY Loves Colors
- HDU 5029 Relief grain(恶心的树链剖分 + 线段树)
- 杭电-2098 分拆素数和 (素数打表)
- 29. Divide Two Integers
- Extjs MVC架构
- hdoj 1997 汉诺塔VII 《递归》
- 一天的记录
- VS2013_MFC编程问题
- 一次给新电脑安装pod--ios辅助开发工具 的过程 (转)
- 浅谈fork与vfork函数
- MySQL日期数据类型、时间类型使用总结
- Android NDK系列(1) --- 配置及简单使用