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 1:

Input: 16
Output: true

Solution:

首先 num & (num - 1) == 0 能保证这个数是2的倍数,举例如下:

假设 num = 20
0001 0100
0001 0011
---------
0001 0000

假设 num = 16
0001 0000
0000 1111
---------
0000 0000

然后 num & 0b01010101010101010101010101010101 = num 能保证这个数(二的倍数)的位都落在4都倍数上

假设 num = 32
0010 0000
0101 0101
---------
0000 0000

假设 num = 64
0100 0000
0101 0101
---------
0100 0000

cpp 代码如下:

bool isPowerOfFour(int num) {
       
    if (num > 0 && (num & (num  - 1)) == 0 && (num & 0b01010101010101010101010101010101) == num)
        return true;
        
    return false;
    
    }

你可能感兴趣的:(LeetCode,算法,leetcode)