[LeetCode] 342. Power of Four(位操作)

传送门

Description

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?

思路

题意:不使用循环和递归,求一个数是否是4的幂次。

题解:我们知道凡是4的幂次,那么其二进制位肯定只有一个1其余都是0,并且可以发现规律,从4的零次幂开始列举,可以发现与上一个幂次相比,隔了一个0,也就是将4的幂次的二进制位写在一起,呈现出...0101...的形式,因此根据  num & (num - 1)可以判定二进制位是否只有一个1,然后再与十六进制的55555555相与即可判断是否有4的幂次的表现形式,因为十六进制的5的表现形式正好是0101。

 

class Solution {
public:
    //3ms
    bool isPowerOfFour(int num) {
        return !(num & (num - 1)) && (num & 0x55555555);
    }
};

  

你可能感兴趣的:([LeetCode] 342. Power of Four(位操作))