gpt4 book ai didi

java - 最小位程序

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:24:51 24 4
gpt4 key购买 nike

我是 Java 新手。我尝试从 Java Just in Time 中学习它。

作者:

So program to calculate how many bits would be needed to represent a given number of different values.

程序是:

int numberOfValues = Integer.parseInt(args[0]);
int noOfBits = 0;

while (Math.pow(2, noOfBits) < numberOfValues)
noOfBits = noOfBits + 1;

但是书作者被要求用其他版本写这个。

作者:

In this task you will write a variation of the MinimumBitWidth program which works a little more efficiently. Instead of computing a power of 2 in the loop condition on each iteration, your version will accumulate 2 to the power of noOfBits in a separate variable. This can be done by initialising your new variable to 1, and simply doubling its value each time you increment noOfBits.

You will use the same test data as used for the previous version of the program.

可能是因为英语不好,我听不懂他的意思。感谢帮助。 :)

最佳答案

意思是将数字与 20, 21, ... 231 进行比较。由于 231 大于 Integer.MAX_VALUE,因此可能会使用 long。

int noOfBits = 0;
long pow2 = 1;
while (numberOfValues >= pow2) {
++noOfBits;
//pow2 = 2 * pow2
//pow2 += pow2;
//pow2 *= 2;
pow2 <<= 1; // Shift left once.
}

另见 Integer.numberOfLeadingZeros(int) ,这会将代码减少为一行代码。

int noOfBits = 32 - Integer.numberOfLeadingZeros(numberOfValues);

关于java - 最小位程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27269598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com