7

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

Community
  • 1
  • 1
NullPointerException
  • 36,107
  • 79
  • 222
  • 382

3 Answers3

15

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

Ragunath Jawahar
  • 19,513
  • 22
  • 110
  • 155
Jeff Grigg
  • 1,004
  • 8
  • 7
6

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.
NPE
  • 486,780
  • 108
  • 951
  • 1,012
5

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.