您的位置:首页 > 其它

342. Power of Four

2016-07-14 22:23 337 查看
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?

Credits:

Special thanks to @yukuairoy for adding this problem and creating all test cases.

如果一个数是2的幂次,它的二进制表示里面只有一位1.

如果一个数是4的幂次,同样它的二进制表示里面只有1位1,但是这个1位不能随意出现,4是100,16是10000,也就是隔位出现,把可能出现的位表示成一个数,用这个数去检查是不是4的幂次而排除例如8这样只是2的幂次的数。

public boolean isPowerOfFour(int num) {
return Integer.bitCount(num)==1&&((num&0x55555555)!=0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: