basics · beginner · ~15 min

Isolate the lowest set bit

Use the x & -x idiom to isolate the lowest set bit.

Challenge

Extract just the lowest set bit of an unsigned integer as its own value.

Task

Implement unsigned lowest_set_bit(unsigned x) that returns the value of the least-significant 1-bit of x. For example, 12 is 1100 in binary, whose lowest set bit has value 4. Return 0 when x is 0 (no bits set). No main — the grader calls it.

Input

A single unsigned x.

Output

Returns the value (a power of two) of the lowest set bit, or 0 if x is 0.

Example

lowest_set_bit(12)     ->   4      (1100 -> 0100)
lowest_set_bit(6)      ->   2      (0110 -> 0010)
lowest_set_bit(1024)   ->   1024
lowest_set_bit(0)      ->   0

Edge cases

  • x == 0 has no set bits, so the result is 0.

Rules

  • No loops needed — the x & -x idiom does it in one expression.

Input format

A single unsigned x.

Output format

The value of the lowest set bit, or 0 when x is 0.

Constraints

Return 0 for x == 0.

Starter code

unsigned lowest_set_bit(unsigned x) {
    /* TODO */
    return 0;
}

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