Cognzant Technology Solutions Interview Question
Software Engineer / DevelopersCountry: India
Interview Type: Written Test
unsigned int v; // we want to see if v is a power of 2
bool f; // the result goes here
f = (v & (v - 1)) == 0;
Note that 0 is incorrectly considered a power of 2 here. To remedy this, use:
f = v && !(v & (v - 1));
Reference: graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
To understand this video you may want to watch this video
youtube.com/watch?v=lTxU9O-dzFc
To know the given integer v is a power of 2, just apply log to v base 2 as shown below:
v = 2^n
==> n = log v base 2
If n is a number (not a decimal) then
v is a power of 2
else
v is not a power of 2
if( v && !( v & (v-1) ) ) => power of 2
- Cerberuz September 10, 2012!( v &(v-1) ) is sufficient except fo v = 0