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
Keep dividing the number by two, i.e, do n = n/2 iteratively until n becomes 1. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2.
The idea is to set all bits on the right-hand side of the most significant set bit to 1 and then drop all but the last set bit from n so that it becomes equal to the previous power of two. For instance, consider number 20. We convert its binary representation 00010100 to 00011111 .
Powers of 2 to required sum in C++ In this problem, we are given an integer N. Our task is to print the number which when raised to the power of 2 gives the number. To solve this problem, we will divide the number with 2 recursively. By this method, every number can be represented as a power of 2.
A really clever programmer would look at the java.lang.Integer.highestOneBit(int)
method, and consider the left-shift operator (<<
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With