[leetcode]Divide Two Integers

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Clarification:

What should we return when needle is an empty string? This is a great question to ask during an interview.

For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C's strstr() and Java's indexOf().


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

class Solution(object):
    def divide(self, dividend, divisor):
        """
        :type dividend: int
        :type divisor: int
        :rtype: int
        """
        flag = (dividend < 0 and divisor > 0) or (dividend > 0 and divisor < 0)
        sums = 0; count = 0; res = 0
        a = abs(dividend); b = abs(divisor)
        while a >= b:
            sums = b
            count = 1
            while sums*2 <= a:
                sums += sums
                count += count
            a -= sums
            res += count
        if flag:
            return -res
        elif res > 2147483647:
            res = 2147483647
        return res

猜你喜欢

转载自blog.csdn.net/weixin_38111819/article/details/80040760