Python solution using math


  • 0
    Z

    from math import log, floor
    
    class Solution(object):
        def isPowerOfFour(self, num):
            # Observation: A power of four is 1 << n where n is even
            # e.g., let E <- [0, 2, 4, 6, ...]. pow(4, k) = 1 << E[k].
            if num <= 0:
                # discard negative numbers and zero
                return False
            # binary log gives the order of magnitude
            d = int(floor(log(num, 2)))
            if d%2 == 0:
                # ensure the trailing bits are 0
                return num == 1 << d
            return False # discard odd orders of magnitude
    

    no tricks, always works.


Log in to reply
 

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