【问题标题】:Java: Offset of highest 1 bit in an integer [duplicate]Java:整数中最高1位的偏移量[重复]
【发布时间】:2013-04-05 12:40:12
【问题描述】:

为了简单起见,我们不考虑 0 或负值。

已知解决方案 #1

return (int)(Math.log(x)/Math.log(2)); // pseudo code

问题:数值不稳定。对于x=4 输入,它可能会回答 2 或 1。

已知解决方案#2

for(int i=0; ;++i)
{
    x = x >> 1;
    if(x==0)
        return i;
}

问题:平均复杂度为 O(n),其中 n 是类型的位数。我希望得到恒定的时间答案。

【问题讨论】:

    标签: java logarithm


    【解决方案1】:

    O(log n)(或更好的!)有许多解决方案,http://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious

    【讨论】:

    • 单独看到O(log n) 给了我一些想法! :-)
    【解决方案2】:

    这是一个基于this的常量时间Java解决方案:

    private static final int MultiplyDeBruijnBitPosition[] = new int[] { 0, 9,
            1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28,
            15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 };
    
    public static int top1(int v) {
        v |= v >>> 1;
        v |= v >>> 2;
        v |= v >>> 4;
        v |= v >>> 8;
        v |= v >>> 16;
        return MultiplyDeBruijnBitPosition[(int)((v * 0x07C4ACDDL) >> 27) & 31];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      • 2020-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-24
      相关资源
      最近更新 更多