Position of least significant bit that is set

后端 未结 23 1268
时光取名叫无心
时光取名叫无心 2020-11-22 08:46

I am looking for an efficient way to determine the position of the least significant bit that is set in an integer, e.g. for 0x0FF0 it would be 4.

A trivial impleme

23条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 09:04

    Here is one simple alternative, even though finding logs is a bit costly.

    if(n == 0)
      return 0;
    return log2(n & -n)+1;   //Assuming the bit index starts from 1
    

提交回复
热议问题