basics · intermediate · ~15 min
Find the smallest power of two >= x.
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.)
x in [1, 2^31].
The next power of two >= x.
x<=1 returns 1; an exact power of two returns itself.
#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; }
Off-by-one: forgetting the initial x-- makes exact powers double.
33 -> 64; 1024 -> 1024.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.