leetcode - 342. Power of Four

Description

Given an integer n, return true if it is a power of four. Otherwise, return false.

An integer n is a power of four, if there exists an integer x such that n == 4^x.

Example 1:

Input: n = 16
Output: true

Example 2:

Input: n = 5
Output: false

Example 3:

Input: n = 1
Output: true

Constraints:

-2^31 <= n <= 2^31 - 1

Solution

Binary Search

Use binary search to find if the number is the power of 4. left, right = 0, 16

Time complexity: o ( log ⁡ k ) o(\log k) o(logk)
Space complexity: o ( 1 ) o(1) o(1)

Bit Manipulation

Ref: https://leetcode.com/problems/power-of-four/solutions/772269/python-o-1-oneliner-solution-explained/?envType=daily-question&envId=2023-10-23
To decide if a number is the power of 4, then it should meet these requirements:

  1. The number is positive;
  2. The number is a power of 2;
  3. The 1 should be at even digits;

For the first one, it’s easy.
For the second one, the number should only have one 1.
For the third, use n & 1010101010101

Time complexity: o ( 1 ) o(1) o(1)
Space complexity: o ( 1 ) o(1) o(1)

Code

Binary Search

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        left, right = 0, 16
        while left < right:
            mid = (left + right) >> 1
            if 4 ** mid < n:
                left = mid + 1
            elif 4 ** mid > n:
                right = mid - 1
            else:
                return True
        return False if 4 ** ((left + right) >> 1) != n else True

Bit Manipulation

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        return n > 0 and n & (n - 1) == 0 and 0b1010101010101010101010101010101 & n == n

你可能感兴趣的:(OJ题目记录,leetcode,算法,职场和发展)