DEV Community

Discussion on: Operations on power of two numbers

Collapse
 
lexlohr profile image
Alex Lohr

Your isPowerOfTwo-Function can be even more simplified:

template <typename T> bool IsPow2(T x)
{
    return (x & 1) == 0;
}

That's because any positive binary number that is a power of two doesn't have the bit representing '1' set.

Otherwise, thanks for the nice post.

Collapse
 
reg__ profile image
Adam Sawicki

This isn't correct. Your code checks if the number is even - 0, 2, 4, 6, 8, 10, 12, 14, ... That's not the same as power of two, which is 1, 2, 4, 8, 16, 32, 64, ...

Collapse
 
lexlohr profile image
Alex Lohr

Ah, that's true, I missed that.