[英]Code for displaying the smallest power of 2 greater than or equal than the integer
I need a code in Java that can find the smallest power of 2 greater than or equal to any non-negative integer entered by the user. 我需要一个Java代码,它可以找到大于或等于用户输入的任何非负整数的2的最小幂。 Can anyone help?
有人可以帮忙吗?
i>1 ? Integer.highestOneBit(i-1)<<1 : 1
Obviously suffers from integer overflow (there isn't a strictly correct solution in int
for around half of positive int
s). 显然会受到整数溢出的影响(对于大约一半的正
int
在int
没有严格正确的解决方案)。
Usual disclaimer: Not tested or compiled. 通常免责声明:未经测试或编译。
See this link 看到这个链接
Algorithm for finding the smallest power of two that's greater or equal to a given value 用于找到大于或等于给定值的2的最小幂的算法
Bye. 再见。
int nextPow2(int n) {
if (n <= 1) return n;
double d = n - 1;
return 1 << ((Double.doubleToRawLongBits(d) >> 52) - 1022);
}
Fastest solution I have found on desktop. 我在桌面上找到的最快的解决方案。
Smallest power of 2 greater than or equal to a
2的最小幂大于或等于
a
// Next higher power of 2 greater than or equal to a
public static int nextPow2(int a) {
int r0, r1, r2, r3, r4;
r0 = 2 * highestOneBit(a - 1);
r1 = highestOneBit(a - 1) << 1;
r2 = (int) pow(2, ceil(log(a) / log(2)));
r3 = (int) pow(2, ceil(log10(a) / log10(2)));
r4 = (int) pow(2, 32 - numberOfLeadingZeros(a - 1));
return r0; // or r1 or r2 or r3 or r4
}
Exponent of the smallest power of 2 greater than or equal to a
最小幂2的指数大于或等于
a
// Exponent of next higher power of 2 greater than or equal to a
public static int nextpow2(int a) {
int r0, r1, r2;
r0 = (int) ceil(log(a) / log(2));
r1 = (int) ceil(log10(a) / log10(2));
r2 = (int) 32 - numberOfLeadingZeros(a - 1); // ceil(log2(x)) = 32 - numberOfLeadingZeros(x - 1)
return r0; // or r1 or r2
}
if (i==0) return 1;
else if (i==1) return 2;
else if (i==2 || i==3) return 4;
else if (i==4 || i==5 || i==6 || i==7) return 8;
else if (...)
你可以通过计算无符号右移的数量直到结果为零来做到这一点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.