Trusted answers to developer questions

Ravi

Check if a number has all bits set in its binary representation.

- Input:
`n=5`

- Output:
`No`

- Input:
`n=7`

- Output:
`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 |

- Time complexity: O(1)
- Space complexity: O(1)

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)); } }

Try it out!

- Lines 3–5: We write a boolean function,
`static boolean`

. It returns`true`

or`false`

according to the bit calculating formula discussed above. - Line 9: We display the output of the result corresponding to the number
`n`

.

Note:The value of`n`

can be changed to any value and tested.

RELATED TAGS

bitwise

CONTRIBUTOR

Ravi

RELATED COURSES

View all Courses

Keep Exploring

Related Courses