[LeetCode] 28. Implement strStr()

题:https://leetcode.com/problems/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.

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,  2311]. For the purpose of this problem, assume that your function returns 2311 when the division result overflows.

思路

题目大意

不用 乘法,除法,取模,求 dividend 除以 divisor 的商。

思路

除了这个上面的操作,只有 左移动能实现 *2的操作。

具体做法:

  1. 对于 若 dividend >= divisor ,tcount = 1。tdivisor = divisor ,将 tdivisor 左移,若 dividend >= tdivisor<1 ,则 tcount = tcount <1,不断循环。直至 dividend >= tdivisor<1 不成立。

  2. dividend -= tdivisor ,totalcount += tcount 。重复1。

code

class Solution:
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        if dividend == -2**31 and divisor == -1:
            return 2**31-1

        tabsdividend = abs(dividend)
        tabsdivisor = abs(divisor)
        absdivisor = tabsdivisor

        totalcount = 0

        while tabsdividend>=tabsdivisor:
            tcount = 1
            tmp = absdivisor
            while tabsdividend >= tmp<<1:
                tmp = tmp<<1
                tcount = tcount<<1

            totalcount += tcount
            tabsdividend -= tmp
        return totalcount if not (dividend>0)^(divisor>0) else -totalcount

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/82587376