BITMASK quiz..qus no 3

Which one line function can be used to get index of the least significant bit that is on (first 1 from right to left in binary representation of an integer) ?

A.log2( N ^ -N ) + 1

B.log2( N | -N ) + 1

C.log2( N & -N ) + 1

D.log2( N ~ -N ) + 1

how C is the answer?

@hrit04
The answer should be log2( N & -N ) + 1 , if n is a positive number , so -n will be a negative number and negative number are represented in 2’s compliment ,which is ~n+1 , ~n has all the bits of n inverted due to which we get 0 in place of 1 and vice versa so when we add 1 to ~n then that 1 occupies the first rightmost 0 in (~n)(which is same as rightmost 1 value in n) and other bits have inverted values or zero values . so when we perform & operation we get only rightmost bit set in the function ,and then we perform logn (base2) to get corresponding index.

eg :- n = 1110010100
~n= 0001101011
~n+1=-n= 0001101100
(n&(-n))= 0000000100 = 4
log(4) =2
2+1=3 which is the answer

you should try applying the formula on some examples on your own for better clarity
dont forget to hit like and mark resolved if cleared :smiley:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.