</>EmbeddedInterview
← All problems · Bit Manipulation

Check Whether an Integer Is Even or Odd Using Bits

Easy

Return 1 if n is even and 0 if it is odd, without division or modulo. Implement int is_even(int32_t n).

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.

Inspect bit zero.

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

int is_even(int32_t n)
{
    return ((uint32_t)n & 1u)==0;
}

Even values have a zero least significant bit, including negative even values after unsigned conversion.

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(is_even(0)==1);
    CHECK(is_even(7)==0);
    CHECK(is_even(-8)==1);
    CHECK(is_even(-3)==0);
    CHECK(is_even(INT32_MIN)==1);
    puts(fails ? "Some tests failed" : "All tests passed");
    return fails != 0;
}