Find the lowest set bit

前端 未结 4 1700
名媛妹妹
名媛妹妹 2021-01-06 21:07

I have 5 bit numbers like

10000
01000
00100

If only one bit is on in my calculation i have no problem.

but if 2 bits are on then I

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-06 21:10

    Since you only want to isolate it, not get its index, it's easy:

    function firstSetBit(number)
    {
        return number & -number;
    }
    

    It works because if you take the two's complement negation of a number, first you complement it, setting all zeroes to the right of the lowest set bit to one and the lowest set bit to zero, then you add one, setting the bits on the right to zero and the lowest set bit becomes one again, ending the carry chain. So the negation of the number has the same "right part", up to and including the lowest set bit, but everything to the left of the lowest set bit is the complement of the input. Thus if you take the bitwise AND of a number with its negation, all the bits to the left of the lowest set bit are cancelled out.

提交回复
热议问题