LeetCode Medium: 29. Divide Two Integers

一、题目

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:

  • Both dividend and divisor will be 32-bit signed integers.
  • The divisor will never be 0.
  • Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231,  231 − 1]. For the purpose of this problem, assume that your function returns 231 − 1 when the division result overflows.

题目大意:不用乘除、取模等运算符,做除法运算

二、思路

这道题可以使用位移运算,借助减法每次减去除数的倍数,每次对商的更新取一个位移操作。

三、代码

#coding:utf-8
def divide(dividend, divisor):
    """
    :type dividend: int
    :type divisor: int
    :rtype: int
    """
    MAX_INT = 2147483647
    sign = 1 if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0) else -1
    quotient = 0
    dividend = abs(dividend)
    divisor = abs(divisor)
    while dividend >= divisor:
        k = 0
        tmp = divisor
        while dividend >= tmp:
            dividend -= tmp
            quotient += 1 << k     #移位运算符比加减优先级高
            tmp <<= 1
            k += 1
    quotient = sign * quotient
    if quotient > MAX_INT:
        quotient = MAX_INT
    print(quotient)
    return quotient

if __name__ == '__main__':
    divide(21,5)

  代码参考:https://blog.csdn.net/qian2729/article/details/50528758

既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8968637.html