• [leetcode]Divide Two Integers @ Python


    原题地址:https://oj.leetcode.com/problems/divide-two-integers/

    题意:Divide two integers without using multiplication, division and mod operator.

    解题思路:不许用乘、除和求余实现两数的相除。那就只能用加和减了。正常思路是被除数一个一个的减除数,直到剩下的数比除数小为止,就得到了结果。这样是无法ac的,因为时间复杂度为O(n),比如一个很大的数除1,就很慢。这里我们可以用二分查找的思路,可以说又是二分查找的变种。

    代码:

    class Solution:
        # @return an integer
        def divide(self, dividend, divisor):
            if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0):
                if abs(dividend) < abs(divisor):
                    return 0
            sum = 0; count = 0; res = 0
            a = abs(dividend); b = abs(divisor)
            while a >= b:
                sum = b
                count = 1
                while sum + sum <= a:
                    sum += sum
                    count += count
                a -= sum
                res += count
            if (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0):
                res = 0 - res
            return res
  • 相关阅读:
    mysql 取出每科成绩前两名
    mysql 数据库以及sql 的优化
    Twitter开源分布式自增ID算法snowflake
    SVN 冲突
    VUE 入门 1 列表、if判断 、双向绑定
    Roadblock
    最大子序和
    SOLDIERS
    绿豆蛙的归宿
    Place the Robots
  • 原文地址:https://www.cnblogs.com/zuoyuan/p/3779359.html
Copyright © 2020-2023  润新知