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

前端 未结 11 1385
梦毁少年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:26

    this can be done as a binary search, reducing complexity of O(N) (for an N-bit word) to O(log(N)). A possible implementation is:

    int highest_bit_index(uint32_t value)
    { 
      if(value == 0) return 0;
      int depth = 0;
      int exponent = 16;
    
      while(exponent > 0)
      {
        int shifted = value >> (exponent);
        if(shifted > 0)
        {
          depth += exponent;
          if(shifted == 1) return depth + 1;
          value >>= exponent;
        }
        exponent /= 2;
      }
    
      return depth + 1;
    }
    

    the input is a 32 bit unsigned integer. it has a loop that can be converted into 5 levels of if-statements , therefore resulting in 32 or so if-statements. you could also use recursion to get rid of the loop, or the absolutely evil "goto" ;)

提交回复
热议问题