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

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    iPhone开发指南应用程序核心
    id,SEL,Nil,nil,IMP,Method,Class类型
    需求驱动赢得创新
    Linux内核list&hlist解读
    转载:x86的cpu_relax解析
    hadoop开发者第三期
    Hadoop开发者入门专刊
    Hadoop源代码eclipse编译指南
    高效的使用stl::map和std::set
    配置VIM语法高亮及自动缩进
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8968637.html
Copyright © 2011-2022 走看看