您的位置:首页 > 其它

leetcode之Power of Two

2016-04-07 01:15 302 查看
Given an integer, write a function to determine if it is a power of two.

Credits:

Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question;
该题判断一个数是否为2的幂,这里利用的是二进制的方法,如果一个数为2的幂,则只有首位为1,所以与其减一的结果相与的结果为0。
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n>0){
return (!(n&(n-1)));
}
else
return false;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: