logo CodeStepByStep logo

nextPowerOf2

Language/Type: C++ bit algorithms

Write a function named nextPowerOf2 that accepts as a parameter an integer n and returns next power of 2 that is greater than or equal to n. For example, if the call is nextPowerOf2(44), you should return 64.

You should solve this problem using bitwise operators and arithmetic. Do not use any collections or strings to solve the problem. You may assume that an int occupies 32 bits in memory. You may assume that the value of n is non-negative. You may assume that there exists a power of 2 that is greater than n in the range of integers. Assume that the integers are stored using ones' complement binary notation.

Function: Write a C++ function as described, not a complete program.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.