basics · beginner · ~15 min
Use the x & -x idiom to isolate the lowest set bit.
Extract just the lowest set bit of an unsigned integer as its own value.
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.
A single unsigned x.
Returns the value (a power of two) of the lowest set bit, or 0 if x is 0.
lowest_set_bit(12) -> 4 (1100 -> 0100)
lowest_set_bit(6) -> 2 (0110 -> 0010)
lowest_set_bit(1024) -> 1024
lowest_set_bit(0) -> 0
x == 0 has no set bits, so the result is 0.x & -x idiom does it in one expression.A single unsigned x.
The value of the lowest set bit, or 0 when x is 0.
Return 0 for x == 0.
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.