题目:
原题链接: https://leetcode-cn.com/problems/divide-two-integers/
解题思路:
根据除数(a)和被除数(b)的正负号,判断最终结果的正负
然后使用除数和被除数的绝对值进行计算
计算的时候,当b > a时,对a进行自加的操作,即a = a + a,第一次相当于×2,第二次×4,直到b < a + a的时候,更新b = b - a, a = 原始值
重复此步骤,直到b < 原始a,退出循环
除此之外,再加一个是否溢出int最大值的判断
如果溢出,则返回int最大值
代码实现:
class Solution:
def divide(self, dividend: int, divisor: int) -> int:
int_range = [2 ** 31 - 1, 2 ** 31]
sign = 0
if dividend < 0 and divisor > 0:
sign = 1
elif dividend > 0 and divisor < 0:
sign = 1
elif dividend == 0 or divisor == 0:
return 0a, b = abs(dividend), abs(divisor)
res = 0
def get_div(a, b):
if a < b:
return 0
tb = b
tmp_res = 1
while a >= tb + tb:
tmp_res = tmp_res << 1
tb = tb << 1
return tmp_res + get_div(a - tb, b)res = get_div(a, b)
if res > int_range[sign]: res = int_range[sign]
if sign == 1: res = 0 - res
return res