Python solution based on bit length


  • 0
    W

    First, we'll use n&(n-1) trick to get exclude numbers that are not power of two. Second, we know bit length of 4 is three. Any power of 4 will have a absolute difference of bit length of integer*2 from 4, including 0. So here we go:

    class Solution(object):
        def isPowerOfFour(self, num):
            """
            :type num: int
            :rtype: bool
            """
            return num&(num-1)==0 and abs(num.bit_length()-3)%2==0
    

    One of the benefits of this paths, instead of using magic number is we can generalize it to power of pow(2,k), e.g. power of 8(=pow(2,3)), see this example: say we wanna see if num is 2 to power of pow(2,k)

    def isPowerOfPow(self, num, k):
            """
            :type num: int
            :rtype: bool
            """
            return num&(num-1)==0 and abs(num.bit_length()-(k+1))%k==0
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.