Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Branchless Bit Toggle

EasyPython00:00
Practice interviewer
In session
5 left
00:00

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.

You need to log in / sign up to run or submit.

Problem

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.

Formal Specification

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.
  • Return the integer produced after toggling all 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.

Constraints

  • 0 <= value < 2 ** width
  • 1 <= width <= 31
  • Only the lowest width bits are toggled
  • Conditional statements, switch-case statements, conditional expressions, and lookup tables are not allowed

Function Signature

def toggle_bits(value, width):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output