342. Power of Four

Question

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example 1:

Input: 16
Output: true

Example 2:

Input: 5
Output: false

Thinking:

  • Method 1:位操作
class Solution {
    public boolean isPowerOfFour(int num) {
        if(num < 0) return false;
        int count = 0;
        for(int i = 0; i < 32; i++){
            if((num & 1) != 0){
                if(++count > 1) return false;
                if(i % 2 != 0){
                    return false;
                }
            }
            num >>>= 1;
        }
        return count == 1;
    }
}