How to get position of right most set bit in C

前端 未结 15 1990
你的背包
你的背包 2020-12-09 04:48
int a = 12;

for eg: binary of 12 is 1100 so answer should be 3 as 3rd bit from right is set.

I want the position of the last most set bit o

15条回答
  •  佛祖请我去吃肉
    2020-12-09 05:21

    Accourding to dbush's solution, Try this:

    int rightMostSet(int a){
          if (!a) return -1;  //means there isn't any 1-bit
          int i=0;
          while(a&1==0){ 
            i++; 
            a>>1;
          }
          return i;
        }
    

提交回复
热议问题