What does the following function mystery() do?
bool mystery(unsigned int x) {
return !(x & (x-1));
}
Read full article from Fun with Bit Operations | LeetCode
bool mystery(unsigned int x) {
return !(x & (x-1));
}
An integer that is a power of two has exactly one bit that is ’1′. Therefore, this function returns whether an integer is a power of two.
The fun does not stop here. Look out for my next post to discover more fun with bit operations!
EDIT: (A small bug fix)
Sharp readers might find that passing 0 into the function returns true (while 0 is not a power of two). In order to remedy this, use:
Sharp readers might find that passing 0 into the function returns true (while 0 is not a power of two). In order to remedy this, use: