Jun 122012

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 Responses to “Turn off the rightmost bit of an integer”

Comments (2)

hi…

your code works perfectly only for values where n>2,

am i right…

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).