Be the first user to complete this post

  • 0
Add to List

Find the right most unset bit OR zero bit of a number

Objective: Given a number, write an algorithm to find the right most unset bit or zero bit in it (In binary representation).

This problem is similar to Find the right most set bit of a number

Example:

Number : 11
Binary representation: 1 0 1 1
Position of right most unset bit: 2

Number : 6
Binary representation: 1 1 0
Position of right most unset bit: 0

Number : 13
Binary representation: 1 1 0 1
Position of right most unset bit: 1

Approach:

If N is a number then the expression below will give the right most unset bit.

~N &  (N +1)
  • Let’s dig a little deep to see how this expression will work.
  • We know that N & ~N = 0
  • If we add 1 from the number, it will make the most unset bit to 1, if there are any set bits on the right side of the unset bit, that bit will become zero.
  • (example : 1 0 1 1 + 0 0 0 1 = 1 1 0 0)
  • So if we negate the original number it will make the rightmost unset bit to 1.
  • Now ~N & (N+1) will make all the bits 0 but the right most unset bit of a number.

Example:

Say N =11, so N = 1 0 1 1
N + 1 = 1 1 0 0
~N = 0 1 0 1
~N & (N+1) = 0 1 0 0 => 2

nd

 bit (assuming right-most index is 0)

Code:


Output:

Right most Unset bit :2.0



Also Read: