题目链接:https://leetcode.com/problems/power-of-four/ 题目:

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个幂次方,发现除了最高位,都是0,且0的个数是偶数,如4=100 16=10000, 8=1000。否则就不是4的power

算法

public static boolean isPowerOfFour(int num) {  
        if(num==1)  
            return true;  
        if(num==2||num==3)  
            return false;  
        if (num<1)  
            return false;  
          
        String binary = Integer.toBinaryString(num);  
        char c[] = binary.toCharArray();  
        int count = 0;  
          
        for(int i=1;i<c.length;i++){//除了开头全是0  
            if(c[i]!='0'){  
                return false;  
            }else{//统计0的个数  
                count++;  
            }  
        }  
          
        if(count!=0&&count%2==0)//有偶数个0  
            return true;  
        else  
            return false;  
}