您的位置:首页 > 其它

【LeetCode】231. Power of Two

2015-07-08 09:49 351 查看
Power of Two

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.

2的次幂的特征就是,二进制表示中只有一位是1.

乘以2相当于左移一位,因此2^k的二进制相当于把1(2^0)向左移动k次

class Solution {
public:
bool isPowerOfTwo(int n) {
if(n <= 0)
return false;
return (n & (n-1)) == 0;
}
};


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