Long.numberOfTrailingZeros() 的 Java 实现

标签 java algorithm

文档链接: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);
}

该算法将 long 分成两个 int 并处理每个 int。我的问题是为什么不使用 y = x << 32 而不是将长分开?

这是我的版本:

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位系统上更快,因为我使用的是Windows 7 64位。至少 Java 应该在他们的 x64 sdk 中使用像我的版本这样的东西。有什么想法吗?

最佳答案

几乎每个应用程序中 0.5% 的性能差异都可以忽略不计。如果您开发的应用程序需要查看此单一方法的性能,您可以自己实现它。

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

相关文章:

java - 如何将此代码从最小堆更改为最大堆

c++ - 为什么 Eigen 在下面的例子中比 ublas 慢 5 倍?

arrays - 算法:从数组中找到最大的子集

java - 使用 MVP 模式在 GWT 中保存导航/历史状态

java - 每当由 DOMConfigurator.configureAndWatch 方法创建的线程重新加载 log4j.xml 时都需要回调

java - 使鼠标事件在整个节点堆栈上可检测

python - 重用已知的排序操作对类似未排序的数据进行排序

c - 在小于 O(log(n)) 的运行时间内从排序数组中进行搜索

java - Cassandra 异常

java - 集合中的内存消耗