How to obtain the next Power Of Two of a given number? [duplicate]
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):
- Start with
1
as the first candidate power of two. - 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.
精彩评论