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

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

    Let n - Decimal number for which bit location to be identified start - Indicates decimal value of ( 1 << 32 ) - 2147483648 bitLocation - Indicates bit location which is set to 1

    public int highestBitSet(int n, long start, int bitLocation)
    {
        if (start == 0)
        {
            return 0;
        }
        if ((start & n) > 0)
        {
            return bitLocation;
        }
        else
        {
            return highestBitSet(n, (start >> 1), --bitLocation);
        }
    }
    
        long i = 1;
        long startIndex = (i << 31);
        int bitLocation = 32;
        int value = highestBitSet(64, startIndex, bitLocation);
        System.out.println(value);
    

提交回复
热议问题