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;
}
};