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

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

    With recursion:

    int firstset(int bits) {        
         return (bits & 0x80000000) ? 31 : firstset((bits << 1) | 1) - 1;
    }
    
    • Assumes [31,..,0] indexing
    • Returns -1 if no bits set
    • | 1 prevents stack overflow by capping the number of shifts until a 1 is reached (32)
    • Not tail recursive :)

提交回复
热议问题