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.

Follow up: Could you solve it without loops/recursion?

补充说明:

给定一个32位的整数,判断这个数是否为4的几次幂。

方案分析

  1. 首先看到这个题目能想到的是如何判断一个数是不是2的几次幂。
  2. 先分析2的几次幂的问题,通常会采用位操作的方式:(num & (num -1)) == 0
  3. 分析是否是4的几次幂,其实思想类似,但需要注意两点:
  • 4的几次幂关注的二进制位为偶数位,如1,3,5,7...31(从0开始)——对应的16进制为0x55555555;
  • 不能只局限关注偶数位的值,还需要借助2的几次幂的问题确保其他位不为1.

python实现

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

你可能感兴趣的:(LeetCode#342 Power of Four)