bool isPowerOfTwo (unsigned int x)
{
return (!(x&(x-1)));
}
I am really confused in this problem according to my concept the answer is yes but the main answer is . this snippet is not correct for 0. help me, anyone, plz
bool isPowerOfTwo (unsigned int x)
{
return (!(x&(x-1)));
}
I am really confused in this problem according to my concept the answer is yes but the main answer is . this snippet is not correct for 0. help me, anyone, plz
You are using unsigned int..
If x=0, x-1=-1 which does fit in the range of unsigned int which is [0,4,294,967,295] hence there will be underflow.
Also, 0 is not a power of 2.
To handle this case use
return x && (!(x&(x-1)));
thankyou bro