Reputation: 916
Given a method of the bool data type that takes in an int variable, what is a single line of code that would determine if the int is an exponent of 2 or 2^n.....2,4,8,16,32 etc. I know of a way using a while loop and if statements, but I'm looking for it to be on one line.
Upvotes: 2
Views: 696
Reputation: 64710
bool answer = ((n & ~(n-1)) == n && n!=0);
This passes all the basic tests I threw at it.
It seems good.
Upvotes: 1
Reputation: 22413
Just check if the log (base 2) of the number is an integer.
In one line of C#:
Math.Log(x, 2) % 1 == 0
Bitwise operations are more fun, but lord have mercy on whomever has to maintain that code.
Upvotes: 6
Reputation: 217351
From Bit Twiddling Hacks:
uint v; // we want to see if v is a power of 2
bool f; // the result goes here
f = (v != 0) && ((v & (v - 1)) == 0);
Upvotes: 9