LeetCode Divide Two Integers
来源:互联网 发布:配音软件有哪些 编辑:程序博客网 时间:2024/04/29 19:26
LeetCode解题之Divide Two Integers
原题
实现两个int型数字的除法,不可以使用乘法、除法和模操作。
注意点:
- 如果结果溢出int类型,返回MAX_INT
- 注意负数情况
例子:
输入: dividend = 5, divisor = -1
输出: -5
解题思路
可以先把符号抽取出来,只考虑两个正数相除的情况。除法其实就是被减数不断减去减数的操作,但直接不断进行减法会超时,应尽量减去大的数字,通过位移操作来快速找到比被减数小一些的减数的倍数current。不断减去且缩小current。溢出只可能是向上溢出,通过min操作进行过滤。
AC源码
class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ MAX_INT = 2147483647 sign = 1 if dividend >= 0 and divisor < 0 or dividend <= 0 and divisor > 0: sign = -1 dividend = abs(dividend) divisor = abs(divisor) result = 0 current = divisor currentResult = 1 while current <= dividend: current <<= 1 currentResult <<= 1 while divisor <= dividend: current >>= 1 currentResult >>= 1 if current <= dividend: dividend -= current result += currentResult return min(sign * result, MAX_INT)if __name__ == "__main__": assert Solution().divide(5, -1) == -5 assert Solution().divide(10, 2) == 5
欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
0 0
- 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
- Divide Two Integers -- LeetCode
- 极光推送遇到的问题
- 自定义syslog保存文件
- outlook 一直发送 "邮箱快满了"
- 管住你自己的情绪
- XCode调试技巧–设置全局断点快速定位问题代码所在行
- LeetCode Divide Two Integers
- js中的循环流程的控制return false,return true,break,continue
- 嵌入式linux编程中的一些基本操作
- sql server 2008登陆服务器名称是什么
- (java)Bulls and Cows
- CIDR地址分类
- cJSON各函数实现的功能
- python第三方库solrpy
- java---成员变量