leetcode -- Divide Two Integers -- 重点,技巧
来源:互联网 发布:双开软件 编辑:程序博客网 时间:2024/05/01 19:19
https://leetcode.com/problems/divide-two-integers/
需要知道的知识:
Without using the *, /, and % operator, what we can use is +,-, and <<, >> .<<1 is to multiply 2,e.g. 2<<1 = 4;>>1 is to divide 2 e.g. 8>>1 = 4;
思路:
常规思路就是用dividend 不断的减去divisor,直到dividend为0. 但是这样太慢,所以我们可以dividend 减去 divisor的2倍,4倍,8倍。。。直到dividend < divisor*2的幂,这个时候dividend还剩下一部分,可能很大,也可能很小,然后再看这剩下的部分除以divisor是多少。于是又继续除以原来的divisor的2倍,4倍,8倍,循环到dividend小于原来的divisor。
参考:http://chaoren.is-programmer.com/posts/43017.html
http://jelices.blogspot.hk/2014/05/leetcode-python-divide-integer.html
http://yucoding.blogspot.hk/2013/01/leetcode-question-28-divide-two-integers.html
所以有两层while循环,一层就是剩下的dividend >= 原来的divisor。下一层就是每次用divisor的2幂倍数减。
这里注意判断越界!!!!!!!!
class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ sign = (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0) a, b = abs(dividend), abs(divisor) ret, c = 0, 0 while a >= b: c = b i = 0 while a >= c: a -= c ret += (1<<i) i += 1 c <<= 1 if sign: ret = -ret return min(max(-2147483648, ret), 2147483647)#判断越界
- 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
- 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
- 中兴2016年校招笔试题目(部分)(二)
- Codeforces #218 (Div. 2) Fox Dividing Cheese
- Android: 在UI线程更新UI的几种方式
- 二分查找
- 黑马程序员——Java语言的环境搭建
- leetcode -- Divide Two Integers -- 重点,技巧
- 九度oj 1181 升序链表
- BZOJ1036: [ZJOI2008]树的统计Count
- 随笔一
- Hibernate工程的手动创建
- MySQL存储引擎
- eclipse 连接到数据库
- 注册验证码校验思路
- 《剑指offer》——孩子们的游戏(圆圈中最后剩下的数)