# Using n&(n-1) trick

• Power of 2 means only one bit of n is '1', so use the trick n&(n-1)==0 to judge whether that is the case

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

• ``````class Solution {
public:
bool isPowerOfTwo(int n) {
return (n>0&&((n&(n-1))==0));
}
};
``````

This is my one line solution..I thought I am the first to post but U guys are really fast...:( :)

• A little golfing...

``````bool isPowerOfTwo(int n) {
return!(n&n-1)*n>0;
}``````

• This post is deleted!

• Hi, sydy71. This is actually what the problem is looking for :-)

• Hi, paladin. The `if-else` can actually be merged into a conditional statement like what sydy71 does.

• Yes, you're right. It's just the first version.
I think it may be better understood than 1-line version, so I uploaded it.

• there was sth wrong with my code, and I don't know what's the problem.I need some help.Here is my code : if(n<=o) return false;
return n&(n-1)==0;

• try return (n&(n-1)) ==0;
n & (n-1)==0 is executed as n & ((n-1)==0) which I am sure is not what you want.
See https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B

• another trick is to use Two's compliment

return n > 0 && (n & (~n + 1)) == n;

• Nice idea!!!

• This post is deleted!

• This post is deleted!

• This post is deleted!

• It's fcking amazing.

• i use the same idea, i remembered my math teacher told me when i was a little child lool

• Great idea :grinning:

• @jeffrey_leo said in Using n&(n-1) trick:

return n > 0 && (n & (~n + 1)) == n;

Hi,
This might be more concise,
return n > 0 && (n & -n) == n;