← All problems · Bit Manipulation
Check Power-of-Two Buffer Size
Return 1 only when x is a nonzero power of two.
Implement int power2(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.
Clear the lowest set bit.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
int power2(uint32_t x)
{
return x && !(x & (x-1));
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
int power2(std::uint32_t x)
{
return x && !(x & (x-1));
}
A power of two has exactly one set bit.
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(power2(0)==0);
CHECK(power2(1)==1);
CHECK(power2(1024)==1);
CHECK(power2(1023)==0);
CHECK(power2(0x80000000u)==1);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}