此代码块如何避免硬编码。编程面试问题 5.1 的要素

How this code block avoiding hard-coding. Elements Of Programming Interviews Question 5.1

我最近开始准备求职面试并遇到了这个示例问题,它要求我们找出数字中有多少位设置为 1 并回答代码块。

The Following program tests bits one at a time starting with the least significant bit. It illustrates shifting and masking; it also shows how to avoid hard-coding the size of the integer word

public static short countBits(int x){

        short numBits = 0;
        while (x != 0){
            numBits += (x & 1);
            x = x >>> 1;
        }
        return numBits;
    }

这里我不明白的是代码如何避免硬编码。维基百科文章谈到了硬编码;

Hard coding is the software development practice of embedding data directly into the source code of a program or other executable object, as opposed to obtaining the data from external sources or generating it at runtime.

在这篇文章中它说如果我们直接从源代码中获取数据,我们就是硬编码。这正是我们在方法中所做的。我们正在从源代码中获取数据:

参数 → int x 是硬编码的。

我不明白的第二部分是我们如何不被硬编码size of the integer word。 这是什么意思?

你没有做 x&1+(x>>>1)&1+(x>>>2)&1+...(x>>>63)&1for(int i=0; i<64; i++) { ... }。这些都假设整数有 64 位 (顺便说一句,由于整数在 java 中只使用 32 位,这会花费不必要的更多时间,但这就是你想避免硬编码的原因).您的方法不关心整数有多少位,它只关心其中某处仍然有 1。