basics · beginner · ~15 min

Strip the lowest set bit

Clear the least-significant 1 bit.

Challenge

Implement:

unsigned clear_lowest_set(unsigned x);

Return x with its lowest set bit cleared. E.g. 0b10100 -> 0b10000.

Input format

x.

Output format

x with the lowest 1 bit turned off.

Constraints

x==0 returns 0.

Starter code

#include <stddef.h>
/* Return x with its lowest set bit cleared (Kernighan step). e.g. 0b10100 -> 0b10000. */
unsigned clear_lowest_set(unsigned x){ return x; }

Common mistakes

Confusing it with isolate (x & -x); the strip form is x & (x-1).

Edge cases to handle

Repeatedly applying it visits each set bit once.

Background lessons

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