How does bit manipulation work?

The question was asked:

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

Returns 2position_of_the_found_bit. "

I wrote a solution below that works great.

int secondRightmostZeroBit(int n) {
  return (int)Math.pow(2,Integer.toBinaryString(n).length()-1-Integer.toBinaryString(n).lastIndexOf('0',Integer.toBinaryString(n).lastIndexOf('0')-1))  ;
}

But below was the best voted solution, which I also liked, since he had only a few characters coding and fulfilling this goal, but I could not understand it. Can someone explain how manipulating bits helps achieve this.

int secondRightmostZeroBit(int n) {
  return ~(n|(n+1)) & ((n|(n+1))+1) ;
}
+4
source share
1 answer

, 0 . 0 , (x... x, , , 0, 1, 1... 1 - 1 0 ):

x...x01...101...1 - that n

1 , :

x...x01...110...0 - that (n+1)

, 0 1

n|(n+1) :

x...x01...111...1 - that n|(n+1)

1 n|(n+1), :

x...x100........0 - that (n|(n+1))+1

, 0 1

~(n|(n+1))

y...y10.........0 - that ~(n|(n+1))

y x

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

0...010.........0

1 0 .

+8

Source: https://habr.com/ru/post/1675232/