Bitwise Solution with Explanation - Python


  • 2
    D
    # looks like a bitwise problem
    # only one bit is set and it has to be one of these values
    # 4     :      100
    # 16    :    10000
    # 64    :  1000000
    # 256   :100000000
    # ...
    # O(1) time; O(1) space
    
    mask = sum([4**i for i in range(0,16)])  # this will be optimized away
    # Decrement and Compare
    # checks if one bit is set
    # http://www.exploringbinary.com/ten-ways-to-check-if-an-integer-is-a-power-of-two-in-c/
    is_power_of_two = not (num & num - 1)
    is_power_of_four = num & mask == num
    return num > 0 and is_power_of_two and is_power_of_four

Log in to reply
 

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