Python [Leetcode 342]Power of Four

题目描述:

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

解题思路:

位操作。

首先判断是不是只有一位数字为1,其余为0

然后判断为1的位置是不是奇数位

代码如下:

class Solution(object):
    def isPowerOfFour(self, num):
        """
        :type num: int
        :rtype: bool
        """
        if num & (num - 1) != 0:
        	return False
        if num & 0x55555555 == 0:
        	return False

        return True

  

原文地址:https://www.cnblogs.com/zihaowang/p/5721715.html