Find the lowest set bit

前端 未结 4 1753
名媛妹妹
名媛妹妹 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:23

    function isolateLowestBit(input)
    {
      mask = 1;
      while (mask <= input)
      {
        if (mask & input)
        {
          // found match - mask is set to the value of the lowest bit
          return mask;
        }
    
        mask *= 2;  // shift up mask by one bit
      }
    
      // no match
      return 0;
    }
    

    Beware that bitwise operations in Javascript are a bad idea, since since Javascript numbers aren't naturally integer.

提交回复
热议问题