One line fast Python solution with explaination

  • 1

    Same as in power of two, we can use bit manipulation to solve this problem.

    • If num is the power of 4, there is only one 1 bit in the binary expression

    • 1 bit must be at the bit standing for the power of 4, i.e. 4, 16, 64. Those bits occur every two bits --> their location is shown below:


    Thus it follows that the length of the binary expression is odd.

    not num & (num - 1) is to check whether it only has one 1 bit;

    len(bin(num)[2:]) & 1) is to check whether the length of the num's binary expression is odd

    def isPowerOfFour(self, num):
        return bool (num > 0 and not num & (num - 1) and (len(bin(num)[2:]) & 1))

Log in to reply

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