您的位置:首页 > 其它

LeetCode之342,Power of Four

2017-02-04 11:37 441 查看
这个题和Power Of Two有很多相同点,可以在其基础上做适当延伸。

原题:

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?

特别注意上面那个:follow up的内容。

解决用的代码是:

class Solution {
public:
bool isPowerOfFour(int num) {
//if 2 or 8,return false
//if 4 or 16,return true
//so 0101 & 1000 =0000
//0101 & 0100 =0100
//get idea above,so
if(num<=0) return false;
return ((num&(num-1))==0 &&(num&0x55555555));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: