Check if a number has all bits set in its binary representation.
n=5
No
n=7
Yes
The base or corner case here is n
, which is zero. There are no bits set.
The trick here is if all the bits of the input number are set, then adding one to it will make it a perfect square of 2. So, the following expression will check if the n
has all bits set or not.
(n & (n+1)) == 0
n | n + 1 | (n & (n+1)) | All bits set? |
---|---|---|---|
5 (101) | 6 (110) | 100 | No |
7 (111) | 8 (1000) | 0000 | Yes |
Let's view the code.
class Main{static boolean isAllBitsSet(int n){return (n & (n + 1)) == 0;}public static void main (String[] args) {int n = 16;System.out.println("Are all bits set in " + n + "? " + isAllBitsSet(n));}}
static boolean
. It returns true
or false
according to the bit calculating formula discussed above.n
.Note: The value of
n
can be changed to any value and tested.