3 Different O(1) Solutions in Python


  • 0
    U

    So I'm presenting three different solutions of this problem in Python

    Solution 1

    Following solution is based on the fact that Square of any power of two would always be a power of 4

    def isPowerOfFour(num):
            """
        :type num: int
        :rtype: bool
        """
        if num <= 0:
            return False
      
        num = math.sqrt(abs(num))
        if int(num) != num:
            return False
        else:
            num = int(num)
            return num & (num - 1) == 0
    

    Solution 2

    Solution 2 is based on the fact that Log base 2 of power of 4 will always be an even number

     def isPowerOfFour(num):
         """
        :type num: int
        :rtype: bool
        """
        return num > 0 and (math.log(num)/math.log(2)) % 2 == 0
    

    Solution 3

    Solution 3 is using the fact that Power of fours will actually be binary numbers with one set bit occuring on odd positions

    def isPowerOfFour(num):
       """
        :type num: int
        :rtype: bool
       """
        if num <= 0:
            return False
            
        num &= ~(-1 << 32)
        masked_num = (num & 0x55555555)
        return False if num != masked_num else (masked_num & (masked_num - 1) == 0)

Log in to reply
 

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