Bit Manipulation
161 / 170Bit ManipulationLesson 1 of 5About 53 min
Six operators, each with one job. Learn the jobs rather than the truth tables.
Those idioms cover most of what these problems need. Python also prints binary directly, which is worth using while learning rather than converting by hand.
n = 13 # 1101 in binaryprint(bin(n), n & 1, n >> 1, bin(n >> 1))print(n & (1 << 2), bool(n & (1 << 1))) # is bit 2 set? bit 1?print(bin(n | (1 << 1)), bin(n & ~(1 << 2))) # set bit 1, clear bit 2print(bin(n ^ n), n ^ 0)Four small functions using the idioms above. is_power_of_two reports whether a positive number has exactly one set bit. lowest_set_bit returns the value of the lowest set bit, or 0. set_bits returns the indexes of every set bit, lowest first. swap_bits returns the number with the bits at two given indexes exchanged.
Tests
print(is_power_of_two(8), is_power_of_two(12), is_power_of_two(0))print(lowest_set_bit(12), lowest_set_bit(8), lowest_set_bit(0))print(set_bits(13), set_bits(0))print(swap_bits(0b1001, 0, 1), swap_bits(0b1010, 1, 3), swap_bits(0b1010, 0, 1))Output
Run tests to see output.
Read the constraints first and let them tell you what complexity is expected. Derive the approach, implement it, run the tests, and submit when it passes.