链接到文档:http://download.oracle.com/javase/6/docs/api/java/lang/Long.html#numberOfTrailingZeros%28long%29
以下是Java实现源代码:

/**
 * Returns the number of zero bits following the lowest-order ("rightmost")
 * one-bit in the two's complement binary representation of the specified
 * <tt>long</tt> value.  Returns 64 if the specified value has no
 * one-bits in its two's complement representation, in other words if it is
 * equal to zero.
 *
 * @return the number of zero bits following the lowest-order ("rightmost")
 *     one-bit in the two's complement binary representation of the
 *     specified <tt>long</tt> value, or 64 if the value is equal
 *     to zero.
 * @since 1.5
 */
public static int numberOfTrailingZeros(long i) {
    // HD, Figure 5-14
int x, y;
if (i == 0) return 64;
int n = 63;
y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
y = x <<16; if (y != 0) { n = n -16; x = y; }
y = x << 8; if (y != 0) { n = n - 8; x = y; }
y = x << 4; if (y != 0) { n = n - 4; x = y; }
y = x << 2; if (y != 0) { n = n - 2; x = y; }
return n - ((x << 1) >>> 31);
}

该算法将长整型分解为两个整型,并处理每个整型。我的问题是,为什么不使用y=x<这是我的版本:
public static int bit(long i)
{
    if (i == 0) return 64;
    long x = i;
    long y;
    int n = 63;
    y = x << 32; if (y != 0) { n -= 32; x = y; }
    y = x << 16; if (y != 0) { n -= 16; x = y; }
    y = x <<  8; if (y != 0) { n -=  8; x = y; }
    y = x <<  4; if (y != 0) { n -=  4; x = y; }
    y = x <<  2; if (y != 0) { n -=  2; x = y; }
    return (int) (n - ((x << 1) >>> 63));
}

我测试了两种方法并取平均值实现时间:595,我的版本时间:593。也许最初的实现在32位系统上更快,因为我使用的是Windows764位。至少java应该在x64 sdk中使用类似我的版本。有什么想法吗?

最佳答案

几乎每个应用程序都可以忽略0.5%的性能差异。如果您在一个应用程序上工作,这个方法需要peek性能,您可以自己实现它。

关于java - Long.numberOfTrailingZeros()的Java实现,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6506356/

10-10 18:18