In connection with a problem I'm solving, I need to check if a binary number with $n$ digits is of a certain form. The number is OK if:
- It is all $0$'s
- The first digit is $1$ and the rest $0$'s
- The first 2 digits are $1$'s and the rest $0$'s
- The first 3 digits are $1$'s and the rest $0$'s
- Etc
Is there a quick way to determine that a number is of this form? I.e. without having to check each digit, starting from the front?
A nonzero number is of the required form if and only if flipping the bits and adding $1$ results in a number with exactly one $1$ bit. Assuming that you are not using some antique computer, flipping the bits and adding $1$ is the same as negating the number. Now there is a quick way of testing whether a number has exactly one $1$ bit. Subtract $1$ and do a bitwise and with the original number. The result is $0$ if and only if the original number had exactly one one bit.
The above operation (
x &= x-1in python) works because subtracting 1 replaces the rightmost $1$ by a $0$, the $0$s to it right by $1$1, and leaves all bits to the left unchanged. Therefore, the operation zeroes the rightmost $1$ bit.EDIT Actually, the operation works for $0$ also, so you don't even have to test a special case. In python you just need
Just to clarify, in the above, $x$ is the negative of the number you started with. In actual code, you'd probably use