[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().


Problem-solving idea: Do not use multiplication, division and remainder to realize the division of two numbers. Then you can only use addition and subtraction. The normal idea is to subtract the dividends one by one until the remaining number is smaller than the divisor, and the result is obtained. This is impossible to ac, because the time complexity is O(n), such as dividing a large number by 1, it is very slow. Here we can use the idea of ​​binary search, which can be said to be a variant of binary search.

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324727376&siteId=291194637
Recommended