考察的是位操作
符号位用is判断, is 用来判断是否是同一个对象
当被除数大于除数进行循环,
用被除数一次一次地减除数,同时增加res的值.
为了加速运算,每次循环用位操作把temp, i向左移一位.
可以依次将被除数减去1,2,4,8..倍的除数,并使
res依次加上1,2,4,8..的数.
Python本身是没有溢出问题的,所以需要在最后判断结果是否溢出.
class Solution(object):
def divide(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)