Python 1-line solution without loops and not tricky


  • 1
    K

    The idea is to go into the binary form of the number.
    If it's a 1 following by even number of zeros, then it's a power of four.
    e.g.

    bin(4**0)
    Out[27]: '0b1'

    bin(4**1)
    Out[28]: '0b100'

    bin(4**2)
    Out[29]: '0b10000'

    bin(4**3)
    Out[30]: '0b1000000'

    Codes:

    class Solution(object):
        def isPowerOfFour(self, num):
            """
            :type num: int
            :rtype: bool
            """
            return bin(num)[3:] == len(bin(num)[3:])*'0' and len(bin(num)[3:])%2==0 if num!=0 else False

Log in to reply
 

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