zoukankan      html  css  js  c++  java
  • Leetcode** 29. Divide Two Integers

    Description: 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, which means losing its fractional part. For example, truncate(8.345) = 8 and truncate(-2.7335) = -2.

    Note: Assume we are dealing with an environment that could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For this problem, assume that your function returns 231 − 1 when the division result overflows.

    Link: 29. Divide Two Integers

    Examples:

    Example 1:
    Input: dividend = 10, divisor = 3
    Output: 3
    Explanation: 10/3 = truncate(3.33333..) = 3.
    
    Example 2:
    Input: dividend = 7, divisor = -3
    Output: -2
    Explanation: 7/-3 = truncate(-2.33333..) = -2.
    
    Example 3:
    Input: dividend = 0, divisor = 1
    Output: 0
    
    Example 4:
    Input: dividend = 1, divisor = 1
    Output: 1

    思路: 不能用乘除和模运算,只能加减。但是连续用被除数减除数,最后会超时,题解里面用了位运算,位运算代替了乘法 a << b,表示 a * 2的b次方。

    class Solution(object):
        def divide(self, dividend, divisor):
            """
            :type dividend: int
            :type divisor: int
            :rtype: int
            """
            MAX_INT = 2147483647
            if (dividend > 0 and divisor > 0) or (dividend < 0 and divisor < 0):
                sign = 1
            else:
                sign = -1
            dividend = abs(dividend)
            divisor = abs(divisor)
            res = 0
            while dividend >= divisor:
                k = 0
                tmp = divisor
                while dividend >= tmp:
                    res += 1 << k
                    dividend -= tmp
                    tmp <<= 1
                    k += 1
            if res*sign > MAX_INT:
                return MAX_INT
            return res*sign

    日期: 2021-04-10 这个题目需要之后重复,标记**,感觉没有完全领会

  • 相关阅读:
    计算机网络 chapter 6 应用层
    计算机网络 chapter 4 网络层
    计算机网络 chapter 2 物理层
    计算机网络 chapter3数据链路层
    计算机网络 chapter 1 概述
    文章
    进程池线程池 协程
    MySQL
    同步锁 死锁与递归锁 信号量 线程queue event事件
    GIL全局解释器
  • 原文地址:https://www.cnblogs.com/wangyuxia/p/14642067.html
Copyright © 2011-2022 走看看