Leetcode29-两数相除
思路:倍增比大小。
比如63/4:
步骤:
4+4=8 < 63 multiply =2 【2x4=8】
8+8=16<63 multiply =4【4x4=16】
16+16=32<63 multiply =8【8x4=32】 res = 8
32+32=64>63 新的dividend=63-32=31
再次循环:
4+4=8 < 31 multiply =2 【2x4=8】
8+8=16<31 multiply =4【4x4=16】res = 8 + 4 = 12
16+16=32>31 新的dividend=31-16=15
再次循环:
4+4=8 < 15 multiply =2 【2x4=8】res = 8 + 4 + 2 = 14
8+8=16>15 新的dividend=15-8=7
再次循环:
4+4=8 > 7 multiply =1 【1x4=4】res = 8 + 4 + 2 + 1 = 15
新的dividend=7-4=3
3<4, 退出循环。
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
flag = 1
if dividend < 0:
flag = -flag
dividend = abs(dividend)
if divisor < 0:
flag = -flag
divisor = abs(divisor)
res = 0
while dividend >= divisor:
cur = divisor
multiple = 1
while cur + cur < dividend:
cur += cur
multiple += multiple
dividend -= cur #被除数
res += multiple
if flag == 1:
res = res
else:
res = -res
if res < -2147483648: # 根据是否溢出返回结果
return -2147483648
elif 2147483647 <= res:
return 2147483647
else:
return res