zoukankan      html  css  js  c++  java
  • 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

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    腾讯微博模拟登录
    python 列表复制给另一个列表,改值两个列表均会改变(备忘)
    python3 re.compile中含有变量
    python3 pyinstaller生成exe文件过程问题解决记录
    python3 不知文件编码情况下打开文件代码记录
    python TKinter部分记录
    python3 列表去除重复项保留原序
    python 字典排序
    python 字典中 重复值去除
    python 一些方法函数
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8968637.html
Copyright © 2011-2022 走看看