如何获得给定数字的下一个二的幂?
可能的重复:
位旋转:找到下一个 2 的幂
如何获得下一个幂给定数字中的两个?
例如,我收到数字 138,下一个 POT 数字是 256。
我收到数字 112,下一个 POT 是 128。
我需要做一个算法来计算
谢谢
Possible Duplicate:
bit twiddling: find next power of two
How to obtain the next Power Of Two of a given number?
For example, i receive the number 138, the next POT number is 256.
i receive the number 112, the next POT is 128.
I need to do an algorithm that calculates that
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
真正聪明的程序员会查看 java.lang.Integer.highestOneBit(int) 方法,并考虑左移运算符 (
<<
)。A really clever programmer would look at the
java.lang.Integer.highestOneBit(int)
method, and consider the left-shift operator (<<
).这是一个非常简单的算法(因为这是家庭作业,您必须自己编写代码):
1
作为 2 的第一个候选幂开始。Here is a very simple algorithm (since this is homework, you'll have to code it up yourself):
1
as the first candidate power of two.假设输入是正整数,一种非常规的解决方案是查看数字的位模式。找到左侧的第一个“1”,然后考虑其左侧的位的值。
Assuming the input is a positive integer, one unconventional solution would be to look at the bit pattern of the number. Find the first '1' from the left, then think about the value of the bit to the left of that.