我必须以某种方式保持我的程序运行,直到指数函数的输出超过输入值,然后将其与指数函数的前一个输出进行比较。即使是在伪代码中,我如何做这样的事情呢?
发布于 2012-01-23 07:25:12
(2,input )中找到以2为底的对数
的值
发布于 2012-01-23 07:46:11
除了循环之外,还有一种解决方案可能更快,这取决于编译器如何映射nlz指令:
public int nextPowerOfTwo(int val) {
return 1 << (32 - Integer.numberOfLeadingZeros(val - 1));
}没有显式的循环,而且肯定比使用Math.pow的解决方案更有效。如果不看一下编译器为numberOfLeadingZeros生成的代码,就很难说更多了。
这样,我们就可以很容易地得到2的较低的幂,然后比较哪一个更接近-在我看来,每个解决方案的最后一部分都必须完成。
发布于 2012-01-23 07:49:47
根据您使用的是哪种语言,您可以使用按位操作轻松完成此操作。您需要输入值中单个1位设置为大于输入值中最高一位设置的值,或者输入值中设置为最高一位的值。
如果您确实将最高设置位以下的所有位都设置为1,则添加1将得到下一个更大的2的幂。你可以右移这个来得到两个的下一个较低的幂,然后选择两个中更接近的一个。
unsigned closest_power_of_two(unsigned value)
{
unsigned above = (value - 1); // handle case where input is a power of two
above |= above >> 1; // set all of the bits below the highest bit
above |= above >> 2;
above |= above >> 4;
above |= above >> 8;
above |= above >> 16;
++above; // add one, carrying all the way through
// leaving only one bit set.
unsigned below = above >> 1; // find the next lower power of two.
return (above - value) < (value - below) ? above : below;
}有关其他类似的技巧,请参阅Bit Twiddling Hacks。
https://stackoverflow.com/questions/8965603
复制相似问题