Your question is Branchless Bit Toggle. Start with the requirements on the right.
Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.
A Publicis Sapient digital experience component stores binary configuration flags as an integer. Toggle every bit within a specified width: each 0 must become 1, and each 1 must become 0.
Implement the operation without using if, else, switch, conditional expressions, or lookup tables. Bits outside the specified width must not affect the result.
Implement toggle_bits(value, width):
value: a non-negative integer whose relevant binary representation uses at most width bits.width: a positive integer representing how many least-significant bits to toggle.width relevant bits.Use bitwise operations. The result must contain exactly the complemented values of the selected bits, including leading zero bits within the requested width.
def toggle_bits(value, width):