[leetcode Q29] Divide Two Integers
来源:互联网 发布:仙界网络直播间书包网 编辑:程序博客网 时间:2024/05/22 01:52
1. 题目
Divide two integers without using multiplication, division and mod operator.
If it is overflow, return MAX_INT.
要求不使用乘除法实现两个整数相除运算。
2. 思路
不使用乘法除法,要想快数得到结果就只能考虑位运算。本题主要考察位运算。
- 被除数减去一次除数,结果 + 1
- 被除数减去
2 x 除数
,结果 + 2 - 被除数减去
4 x 除数
,结果 + 4 - ……
需要注意整数溢出
如输入:
-21474836481-2147483648-1
3. 实现
class Solution {public: int divide(int dividend, int divisor) { // Note: The Solution object is instantiated only once. if (divisor == 1) return dividend; long long a = abs((double)dividend); long long b = abs((double)divisor); long long res = 0; while(a >= b) { long long c = b; for(int i = 0; a >= c; i++, c <<=1) { a -= c; res += 1<<i; } } if (res == 0x80000000) return 2147483647; else return ((dividend ^ divisor) >> 31) ? (-res) : (res); } };
0 0
- [leetcode Q29] Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode: Divide Two Integers
- [LeetCode] Divide Two Integers
- [Leetcode] Divide Two Integers
- LeetCode Divide Two Integers
- 【leetcode】Divide Two Integers
- [LeetCode]Divide Two Integers
- LeetCode-Divide Two Integers
- LeetCode: Divide Two Integers
- Divide Two Integers - leetcode
- Leetcode: Divide Two Integers
- LeetCode:Divide Two Integers
- leetcode Divide Two Integers
- LeetCode Divide Two Integers
- LeetCode | Divide Two Integers
- Leetcode: Divide Two Integers
- notepad++ Emmet插件开发html、css。
- MyBatis之ResultMap简介,关联对象
- iOS开发技巧系列---打造强大的BaseModel
- Android4.1输入系统参数配置和输入事件校准
- UITableView刷新指定section、cell
- [leetcode Q29] Divide Two Integers
- Ubuntu下QT的安装详细教程
- 需求管理之获取用户需求的十大沟通技巧
- 机器学习常见算法分类汇总
- JDK5新特性之增强for
- 需求管理之项目中如何更好的控制客户需求
- JDK5新特性之静态导入
- 机器学习经典书籍
- 需求管理之可行性分析和需求分析