Python solution with detailed explanation


  • 0
    G

    Solution

    Power of Four https://leetcode.com/problems/power-of-four/

    Algorithm

    • Must also be a power of 2 and have just one set bit. Use n&(n-1).
    • Only the even numbered bit should be set like 2^2 or 2^4 or 2^6. Use mask 0x55555555.
    • Notice 0x55555555 is: 01010101010101010101010101010101. num & mask != 0.
    class Solution(object):
        def isPowerOfFour(self, num):
            """
            :type num: int
            :rtype: bool
            """
            if num == 1:
                return True
            val = 1
            mask = 0x55555555
            return (num&(num-1) == 0) and ((num & mask) != 0)
    

Log in to reply
 

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