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

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

    Floor of logarithm-base-two should do the trick (though you have to special-case 0).

    Floor of log base 2 of 0001 is 0 (bit with index 0 is set).
     "           "      of 0010 is 1 (bit with index 1 is set).
     "           "      of 0011 is 1 (bit with index 1 is set).
     "           "      of 0100 is 2 (bit with index 2 is set).
    and so on.
    

    On an unrelated note, this is actually a pretty terrible interview question (I say this as someone who does technical interviews for potential candidates), because it really doesn't correspond to anything you do in practical programming.

    Your boss isn't going to come up to you one day and say "hey, so we have a rush job for this latest feature, and it needs to be implemented without loops!"

提交回复
热议问题