Traversing a matrix in spiral order
June 12, 2012
Check if number is a power of 4
June 12, 2012

Turn off the rightmost bit of an integer

How will you turn off the rightmost bit in the binary representation of an unsigned int number.

Solution:

We have to turn off the right most bit in binary representation of a number. For example

Input:  18 (00…010010)
Output: 16 (00…010000)
Input:  15 (00…001111)
Output: 14 (00…001110)

The solution uses the fact that in the binary representation of (n-1)  all bits from right till x will be toggled, where x is the rightmost set bit in binary representation of n. For example:

n   = 18 (00…010010)
n-1 = 17 (00…010001)
n   = 15 (00…001111)
n-1 = 14 (00…001110)
n   = 8 (00…001000)
n-1 = 7 (00…000111)

If we want to turn off the rightmost set bit, then we just need to do a bit-wise AND of n & n-1.

    unsigned int turnOffRightMostSetBit(unsigned int n)
    {
        return n&(n-1);
    }

2 Comments

  1. vishwa says:

    hi…
    your code works perfectly only for values where n>2,
    am i right…

    • Kamal Rawat says:

      No.. It should work for all positive values of n.
      if n == 2 (000…010)
      then n & (n-1) will be (000…010) & (000…001) = 000…000 (hence unset the rightmost bit.
      Similarly if n is one then also it will unset the rightmost bit (the only set bit).

Leave a Reply to Anonymous Cancel reply

Your email address will not be published. Required fields are marked *