basics · intermediate · ~15 min

Round up to a power of two

Find the smallest power of two >= x.

Challenge

Implement:

unsigned round_up_pow2(unsigned x);

Return the smallest power of two that is >= x, for 1 <= x <= 2^31. (x<=1 returns 1.)

Input format

x in [1, 2^31].

Output format

The next power of two >= x.

Constraints

x<=1 returns 1; an exact power of two returns itself.

Starter code

#include <stddef.h>
/* Smallest power of two >= x, for 1 <= x <= 2^31. (x<=1 returns 1.) */
unsigned round_up_pow2(unsigned x){ (void)x; return 1; }

Common mistakes

Off-by-one: forgetting the initial x-- makes exact powers double.

Edge cases to handle

33 -> 64; 1024 -> 1024.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.