shortest way to check if a positive integer is a power of two

时间:2015-10-30 21:48:34

标签: c++ bit-manipulation

This question is from job interview...
Use this template to write a C++ function that checks if a positive integer is a power of two.

bool p(int n)
{
    return ********;
}

You have to replace the 8 '*' symbols with other symbols in order to make the function work correctly.
My best approach was this:

bool p(int n)
{
    return !(n&=n-1);
}

Unfortunately it was wrong, because there are 9 symbols here...
Any ideas?

1 个答案:

答案 0 :(得分:0)

Why assign to n? Just remove = and you have one character less. It will create a temporary instead, the logic won't change.