Divide Two Integers @ LeetCode (Python)
kitt
posted @ 2014年2月22日 19:47
in LeetCode
, 3721 阅读
一开始我用被除数一次一次地减除数,这样太慢了,遇到被除数为2147483648除数为1的情况就挂了。可以用被除数不断地减除数的1倍、2倍、4倍、8倍...这样就快了。使用位运算,被除数与除数同号时商为正,异号时商为负。
class Solution: # @return an integer def divide(self, dividend, divisor): sign = 1 if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0) else -1 dividend = abs(dividend) divisor = abs(divisor) quotient = 0 while dividend >= divisor: k = 0; tmp = divisor while dividend >= tmp: quotient += 1 << k dividend -= tmp tmp <<= 1 k += 1 return quotient * sign