Easy · Lowest Set Bit
Understand → Visualise → Practice.
Return whether positive integer n contains exactly one set bit.
A positive power of two looks like 1000…0 in binary. Subtracting 1 flips that bit and sets all lower ones, so n & (n − 1) is 0 only for powers of two.
0 and negative numbers are never powers of two.
Compute n & (n − 1).
If nothing remains, n had exactly one set bit.
O(1) time and O(1) space.
Without the n > 0 check, n = 0 passes the n & (n − 1) == 0 test.
Read the full guide first: Bit Manipulation and Bitmask Patterns.
Guest mode lets you understand, visualise and run the sample tests. Create a free account to submit and save your solutions.