basics · beginner · ~15 min
Clear the least-significant 1 bit.
Implement:
unsigned clear_lowest_set(unsigned x);
Return x with its lowest set bit cleared. E.g. 0b10100 -> 0b10000.
x.
x with the lowest 1 bit turned off.
x==0 returns 0.
#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; }
Confusing it with isolate (x & -x); the strip form is x & (x-1).
Repeatedly applying it visits each set bit once.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.