Tips! Judge whether a number is the power of 4?

Time:2021-2-24

Long lost Shuangbai, QAQ
Leetcode-342

The topic said not to use loops or recursion as much as possible, so I thought of the previous judgment that a number is not a power of 2. Therefore, let’s see if there is any similarity.

The power of 4 must be the power of 2, but the reverse is not true. For example, 8 is to the third power of 2, but not to the power of 4.

The conversion from 1 to 2 is 1;
4 to binary is 100;
6 to binary is 110;
8 to binary is 1000;
The conversion from 16 to 2 is 10000;

To judge whether a number is the power of 2, we need to see if all digits have only one 1 after the number is converted to binary.
The law of the power of 4 is to see if there is only one 1 in all digits after the number is converted to binary, and the 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;
    }
};

Compared with circulation and other methods, this kind of solution certainly saves a lot of effort.