码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Power of Four

时间:2016-05-27 11:24:23      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

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


【Leetcode】Power of Four

标签:

原文地址:http://blog.csdn.net/yeqiuzs/article/details/51510919

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!