# Tips! Determine whether a number is a power of 4?

Posted Jun 15, 2020 • 1 min read

Long-lost Double Hundred, QAQ

Leetcode-342

The topic said that you should not use loops or recursion as much as possible, so I thought of the previous judgment about whether a number is a power of two, so let's see if there is any similarity.

A power of 4 must be a power of 2, but the reverse is not true. For example, 8 is the power of 2, but not the power of 4.

1 converted to 2 hexadecimal is 1;

4 converted to 2 hexadecimal is 100;

6 converted to 2 hexadecimal is 110;

8 converted to 2 hexadecimal is 1000;

Converting 16 to 2 is 10000;

To determine whether a number is a power of 2, we have to see whether the number of digits is only 1 after the number is converted to binary.

The law of the power of 4 is to see whether all digits are only 1 after the number is converted to binary, and this 1 can only appear on odd digits.

code:

```
class Solution {
public:
bool isPowerOfFour(int num) {
if(num == 1) return true;
if(num <= 3) return false;
int count = 0;
int i = 1;
while(num != 0){
if((num&1) != 0 &&(i&1) != 0){
count++;
}
if((i&1) == 0 &&(num&1) != 0){
return false;
}
num>>=1;
i++;
}
if(count == 1)
return true;
return false;
}
};
```

This kind of solution is definitely more labor-saving than the loop method.