How to get the next Strength Two from a given number?

Possible duplicate:
twiddling bit: find the next power of two

How to get the next Strength Two from a given number?

For example, I get the number 138, the next POT number is 256.

i gets number 112, the next POT is 128.

I need to make an algorithm that calculates that

thanks

+7
source share
3 answers

In fact, a smart programmer will look at the java.lang.Integer.highestOneBit(int) method and consider the left shift operator ( << ).

+15
source

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

  • Start with 1 as the first candidate opportunity of two.
  • Continue to shift the candidate number one bit to the left until it becomes larger or equal to the target number.
+6
source

Assuming input is a positive integer, one unconventional solution would be to look at the number bitmap. Find the first “1” on the left, then think about the value of the bits to the left of it.

+5
source

All Articles