开发者

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

开发者 https://www.devze.com 2023-01-18 13:45 出处:网络
Given a method of the 开发者_如何学Cbool 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 o

Given a method of the 开发者_如何学Cbool 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.


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


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.


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


bool answer = ((n & ~(n-1)) == n && n!=0);

This passes all the basic tests I threw at it.

It seems good.

0

精彩评论

暂无评论...
验证码 换一张
取 消