Power of Four(Easy)

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:

Given num = 16, return true. Given num = 5, return false.

Follow up:

Could you solve it without loops/recursion?

  • First, the number must be power of two. using (n & n - 1) to count 1s in binary string.
  • Secondly, we must make sure that the only bit 1 appears at some odd position. So using a mask 0x55555555.

Python 3 Code

class Solution:
    # @param {integer} n
    # @return {boolean}
    def isPowerOfFour(self, n):
        if ((n <= 0) or (n & n - 1) != 0):
            return False
        else:
            return (n & 0x55555555) != 0

test =  Solution()
print(test.isPowerOfFour(32))

Another Solution

  • num must be positive
  • num must be power of 2
  • num mod 3 must be 1

Python 3 Code

class Solution:
    def isPowerOfFour(self, num):
        if (num <= 0):
           return False
        if (num & num - 1):
          return False;
        return num % 3 == 1

test =  Solution()
print(test.isPowerOfFour(64))

results matching ""

    No results matching ""