find the index of the highest bit set of a 32-bit number without loops obviously

前端 未结 11 1425
梦毁少年i
梦毁少年i 2021-01-07 01:56

Here\'s a tough one(atleast i had a hard time :P):

find the index of the highest bit set of a 32-bit number without using any loops.

11条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-07 02:31

    Paislee's solution is actually pretty easy to make tail-recursive, though, it's a much slower solution than the suggested floor(log2(n));

    int firstset_tr(int bits, int final_dec) {
    
         // pass in 0 for final_dec on first call, or use a helper function
    
         if (bits & 0x80000000) {
          return 31-final_dec;
         } else {
          return firstset_tr( ((bits << 1) | 1), final_dec+1 );
         }
    }
    

    This function also works for other bit sizes, just change the check, e.g.

    if (bits & 0x80) {   // for 8-bit
      return 7-final_dec;
    }
    

提交回复
热议问题