• 29. 两数相除






    思路:

    eg:11÷3
    
    ∵11>3
    
    ∴res>=1
    
    又∵11>3+3=6
    
    ∴res>=2 (1+1)
    
    又∵11<6+6=12
    
    ∴res<4 (2+2)
    
    即2<=res<4
    
    递归部分:
    
    又11-6=5>3
    
    ∴restemp >= 1
    
    又∵5<6 (3+3)
    
    ∴restemp<2 (1+1)
    
    即1<=restemp<2
    
    又∵5-3=2<3
    
    ∴restemp = 1
    
    返回:
    
    ∴res = 2 + restemp = 2+1=3
    

    class Solution(object):
        def divide(self, dividend, divisor):
            """
            :type dividend: int
            :type divisor: int
            :rtype: int
            """
            if dividend == 0:
                return 0
            # 符号
            sign = 1
            if (dividend > 0 and divisor < 0) or (dividend < 0 and divisor > 0):
                sign = -1
            # 溢出的情况
            if abs(divisor) == 1:
                if abs(dividend) > 2 ** 31 - 1:
                    return 2 ** 31 - 1 if sign > 0 else -2 ** 31
            tema = abs(dividend)
            temb = abs(divisor)
            res = self.DiGuiDiv(tema, temb)
            return res if sign > 0 else -res
    
        def DiGuiDiv(self, a, b):
            if a < b:
                return 0
            count = 1
            temp = b
            while (temp + temp) <= a:
                count += count
                temp += temp
            return count + self.DiGuiDiv(a - temp, b)
    
    
    if __name__ == '__main__':
        solution = Solution()
        print(solution.divide(-2147483648, -1))
    
  • 相关阅读:
    JAVA日常之三
    java将字符串存入oracle的Blob中
    java连接oracle数据库
    JAVA日常之二
    JAVA日常之一
    linux日常命令之三
    linux日常命令之二
    linux日常命令之一
    Python之路【第四十篇】:django日更
    Python之路【第三十九篇】:django日更
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13065179.html
Copyright © 2020-2023  润新知