1 Star 0 Fork 0

wd6/LeetCode-1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
divide-two-integers.py 1.42 KB
一键复制 编辑 原始数据 按行查看 历史
Jack 提交于 8年前 . add some solutions
# Time: O(logn) = O(1)
# Space: O(1)
#
# Divide two integers without using multiplication, division and mod operator.
class Solution:
def divide(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
result, dvd, dvs = 0, abs(dividend), abs(divisor)
while dvd >= dvs:
inc = dvs
i = 0
while dvd >= inc:
dvd -= inc
result += 1 << i
inc <<= 1
i += 1
if dividend > 0 and divisor < 0 or dividend < 0 and divisor > 0:
return -result
else:
return result
def divide2(self, dividend, divisor):
"""
:type dividend: int
:type divisor: int
:rtype: int
"""
positive = (dividend < 0) is (divisor < 0)
dividend, divisor = abs(dividend), abs(divisor)
res = 0
while dividend >= divisor:
temp, i = divisor, 1
while dividend >= temp:
dividend -= temp
res += i
i <<= 1
temp <<= 1
if not positive:
res = -res
return min(max(-2147483648, res), 2147483647)
if __name__ == "__main__":
print Solution().divide(123, 12)
print Solution().divide(123, -12)
print Solution().divide(-123, 12)
print Solution().divide(-123, -12)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Python
1
https://gitee.com/wd6/LeetCode-1.git
git@gitee.com:wd6/LeetCode-1.git
wd6
LeetCode-1
LeetCode-1
master

搜索帮助