开发者

How to obtain the next Power Of Two of a given number? [duplicate]

This question already has answers here: Closed 11 years ago.

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 t开发者_如何学运维hat

Thanks


A really clever programmer would look at the java.lang.Integer.highestOneBit(int) method, and consider the left-shift operator (<<).


Here is a very simple algorithm (since this is homework, you'll have to code it up yourself):

  1. Start with 1 as the first candidate power of two.
  2. Keep shifting the candidate number by one bit to the left until it's greater than, or equal to, the target number.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜