标签:color cat 保存 style sel 问题 == ica not
这题
Given two integers dividend
and divisor
, divide two integers without using multiplication, division and mod operator.
Return the quotient after dividing dividend
by divisor
.
The integer division should truncate toward zero.
Example 1:
Input: dividend = 10, divisor = 3 Output: 3
Example 2:
Input: dividend = 7, divisor = -3 Output: -2
Note:
这题提示不能用乘法,除法,取余,所以可以用的是可以用加法,减法, >>1, <<1的位运算。
因为只能用位运算代替乘除,所以我们用2的幂次来组成结果。从最大头的部分开始,之后减去后,依次求解。这题另外提示可能会overflow所以要处理边界问题,能出现2^ 31的情况只有被除数为:
-2^31,除数为-1的情况(The divisor will never be 0)。代码如下:
class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ int_max = 2**31-1 int_min = -2**31 if divisor == 0 or (dividend == int_min and divisor == -1): return int_max sign = 1 if ((dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0)) else -1 divid = abs(dividend) divis = abs(divisor) res = 0
#注意这里要保存为相等,防止开始被除数和除数相等的情况 while divid >= divis: cur = divis cnt = 1
#处理整除的情况 while cur <= divid: cur = cur << 1 cnt = cnt << 1 res += cnt >> 1 divid -= cur >> 1 if sign > 0: return res else: return -res
注意代码对整除,被除数和除数相等的情况要做下处理,所以要保存等号
标签:color cat 保存 style sel 问题 == ica not
原文地址:https://www.cnblogs.com/sherylwang/p/9736712.html