Nard Dog
Nard Dog

Reputation: 916

Return if a given int is an exponent of 2 C#

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

Answers (4)

abelenky
abelenky

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

Ian Henry
Ian Henry

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

Maciej Hehl
Maciej Hehl

Reputation: 7995

bool powerOfTwo = (unchecked(n & (n-1)) == 0) && (n != 0)

Upvotes: 4

dtb
dtb

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

Related Questions