python 2 line solution, with explaination


  • 0
    A
    return (num!=0) and ((num & (num - 1)) == 0) and (len(str(bin(num)[2:]))%2 ==1)
    

    if a number is a power of 2, only the leftmost character of it's binary representation is 1, rest are 0. for example:
    10 => 2,
    100=> 4,
    1000=> 8
    100000=>16
    that condition is handled by the line:

    (num & (num - 1)) == 0

    when a number is a power of 4, it's definitely a power of 2. notice the four numbers above:
    4 and 16 are power of both 2 and 4.
    binary value of 4 and 16 contains 3 & 5 digits respectively
    whereas
    binary value of 2 and 8 contains 2 & 4 digits respectively.
    so if a number is a power of 2 and it's binary value contains odd number of digits, then it's a power of 4.
    that's why I added the line:

    len(str(bin(num)[2:]))%2 ==1


Log in to reply
 

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