Pages

Sunday, August 22, 2010

How to check if an integer is a power of 2 ?

 

Source: http://www.codechef.com/wiki/tutorial-bitwise-operations

Explanation:

The Integer which is the power of two will always have the leftmost bit 1 and the remaining bits as 0. Let this number be x.

And the number (x-1) will never have the leftmost bit as 1. So x & (x-1) will always give 0 if the number is power of 2.

So to check whether the number is power of two, check x & (x-1) , if the answer is 0 then the number is infact power of 2.

No comments:

Post a Comment