Python solution by counting the 0 of binary


  • 0
    J

    Power of 2 (1, 2, 4, 8, 16) their binary are (1, 10, 100, 1000)

    compare them to the

    Power of 4 (1, 4, 16, 64) their binary are (1, 100, 10000, 1000000)

    I found out that the 0's after the first 1 bit for power of 4 are always even, but the power of 2 can be either odd or even.

    Example: for power of 2, binary for 2^2 is 0010 the 0's count after the first 1bit are 1. it is an odd number.

    So if we check if 0's count after the first 1 are even number then it will be a power of 4.

    class Solution(object):
        def isPowerOfFour(self, num):
            """
            :type num: int
            :rtype: bool
            """
            b = bin(num)[2:]
            c = collections.Counter(b)
            if num < 0:
                return False
            if c['1'] > 1:
                return False
            elif c['0'] % 2 != 0:
                return False
            else:
                return True
    

    This is absolutely not the good/fast solution, I also do not know if it is actually correct solution but it passed every test cases for this question


  • 0

    Try to use this property.

    4^r - 1 = 3 * C


  • 0
    W
    return  1==bin(num)[2:][::-1][::2].count('1') and bin(num).count('1')==1 and num>0
    

    you can count '1' in fact


Log in to reply
 

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