LeetcodePower of Four

Posted wuezs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetcodePower of Four相关的知识,希望对你有一定的参考价值。

题目链接: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;  
}  


以上是关于LeetcodePower of Four的主要内容,如果未能解决你的问题,请参考以下文章

342. Power of Four

342 Power of Four 4的幂

Four steps of gcc

342. Power of Four

342. Power of Four

342. Power of Four