您的位置:首页 > 其它

leetcode 342. Power of Four 判断一个数是否为4的幂

2016-04-23 17:22 381 查看
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?
这到题和Power of two类似,如果不能用递归循环做,就使用位操作。1个数是2的幂肯定是4的幂,但反过来不成立,4的幂只能是奇数位为1,而2的幂只有有一个位置为1就行。

所以先判断是否为2的幂,然后通过与.0X55555555(....1010101)进行&操作,保留奇数位,判断是否改变。

public boolean isPowerOfFour(int num) {
if(num<=0)
return false;
return (num & num-1)==0 && (num&0x55555555)==num;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: