您的位置:首页 > 其它

【Leetcode】Power of Four

2016-05-26 21:52 381 查看
题目链接: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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: