- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我是 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 to1
, and simply doubling its value each time you incrementnoOfBits
.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/
我是一名优秀的程序员,十分优秀!