• 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

    既然无论如何时间都会过去,为什么不选择做些有意义的事情呢
  • 相关阅读:
    Codeforces Beta Round #92 (Div. 2 Only) B. Permutations 模拟
    POJ 3281 Dining 最大流 Dinic算法
    POJ 2441 Arrange the BUlls 状压DP
    URAL 1152 Faise Mirrors 状压DP 简单题
    URAL 1039 Anniversary Party 树形DP 水题
    URAL 1018 Binary Apple Tree 树形DP 好题 经典
    pytorch中的forward前向传播机制
    .data()与.detach()的区别
    Argparse模块
    pytorch代码调试工具
  • 原文地址:https://www.cnblogs.com/xiaodongsuibi/p/8968637.html
Copyright © 2020-2023  润新知