您的位置:首页 > 其它

LeetCode 342. Power of Four(4的n次幂)

2016-04-30 11:08 274 查看
原题网址:342. Power of Four 342. Power of Four 342. Power of Four 342.
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?
方法:判断是否只有个1个比特为1,并且1后面有偶数个0。

public class Solution {
public boolean isPowerOfFour(int num) {
return num > 0 && (num & -num) == num && (num & 0x55555555) != 0;
}
}

另一种实现:

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