Fog Creek Software
Discussion Board




Find if the given number is a power of 2

I am sure it has got something to do with bitwise operators, but for some reason, my brain aint working.

Note that we should not use loops. It should be a simple C statement.

Thanks

Nick Mason
Monday, May 17, 2004

take the biggest power of 2 that will fit in an int. Does your number divide it evenly? If so then it's a power of 2.

Ham Fisted
Monday, May 17, 2004

.... or an alternative:

int
is_power2( int x )
{
    return (x != 0) && ( ( (x-1) & x ) == 0 );
}

msafar
Monday, May 17, 2004

That's darn clever. Although (unless you consider 1 to be a power of 2) I suggest

int
is_power2( int x )
{
    return (x != 0) && (x != 1) && ( ( (x-1) & x ) == 0 );
}

David Clayworth
Thursday, May 20, 2004

David,

number 1 is a power of 2:

2^0 == 1.

msafar
Thursday, May 20, 2004

*  Recent Topics

*  Fog Creek Home