## Problem: Find the second rightmost bit in a number (1 line code)

Presented with the integer `n`

, find the 0-based position of the second rightmost zero bit in its binary representation (it is guaranteed that such a bit exists), counting from right to left.

Return the value of `2`

.^{position_of_the_found_bit}

**Example**

For `n = 37`

, the output should be

`secondRightmostZeroBit(n) = 8`

.

`37`

. The second rightmost zero bit is at position _{10} = 10**0**101_{2}`3`

(0-based) from the right in the binary representation of `n`

.

Thus, the answer is `2`

.^{3} = 8

def secondRightmostZeroBit(n): return 2**(len(bin(n)[2:])-1-bin(n)[2:].rfind('0',0,len(bin(n)[2:])-(len(bin(n)[2:]) - bin(n)[2:].rfind('0'))))

Advertisements

## Kevin Bui 11:42 am

onOctober 11, 2016 Permalink |There’s actually a way to do this with just pure bit-operations. First, n | (n+1) turns off the rightmost 0 bit (since we want to find the second rightmost). Then by negating that and AND’ing it with the number that’s +1 isolates the rightmost 0 bit:

return (n | (n+1) + 1) & ~(n | (n+1))

Example: (for 10110111 we want to get 01000000)

n: 10110111

n+1: 10111000

n | (n+1): 10111111

~(n | (n+1): 01000000

(n | (n+1) + 1: 11000000

(n | (n+1) + 1) & ~(n | (n+1)): 01000000

## loctv 10:20 am

onOctober 12, 2016 Permalink |Cool! I’m really bad at bit map manipulation, but I think this problem cant be solved with pure bit-operations like this, since the problem requires just one line of code and python does not have built-in flip bit operator.

## Kevin Bui 11:29 am

onOctober 12, 2016 Permalink |Instead of the negate operator, you can substitue it with -n -1 since they’re equivalent, though more verbose ðŸ˜¦

## loctv 11:46 am

onOctober 12, 2016 Permalink |Oops! my bad, it does have flip bit operator. Nice solution ðŸ™‚