</>EmbeddedInterview
← All problems · Bit Manipulation

Round Capacity Up to Power of Two

Medium

Return the smallest power of two at least x, with minimum 1. Return zero on overflow. Implement uint32_t capacity(uint32_t x).

Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.

Spread the highest set bit after subtracting one.

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

uint32_t capacity(uint32_t x)
{
    if(x<=1)return 1; if(x>0x80000000u)return 0; --x; for(unsigned s=1;s<32;s*=2)x|=x>>s; return x+1;
}

The spread fills lower bits; adding one rounds up.

solution.c
OutputPress Run to compile and test your code.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
    
    CHECK(capacity(0)==1);
    CHECK(capacity(17)==32);
    CHECK(capacity(16)==16);
    CHECK(capacity(0x80000001u)==0);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}