Efficient bitwise operations for counting bits or find the right|left most ones

前端 未结 5 1029
抹茶落季
抹茶落季 2020-11-29 08:57

Given an unsigned int, I have to implement the following operations :

  1. Count the number of bits set to 1
  2. Find the index of the left-most 1 bit
5条回答
  •  情深已故
    2020-11-29 09:37

    for rightmost bit simple ans

    First Method

    unsigned int getFirstSetBit(int n){
    
    return log2(n & -n) + 1; 
    

    }

    Second Method

    unsigned int getFirstSetBit(int n){
    
    return ffs(n);   
    

    }

提交回复
热议问题