1524. Flip a Bit Window

Easy1.5 points estimatedBit ManipulationBitmask

A control panel stores the state of up to 31 switches in one integer n, where bit 0 is the least significant bit and a set bit means the switch is on. An operator presses a single button that toggles every switch in a contiguous window, from position lo up to position hi inclusive, turning on switches that were off and off switches that were on. Switches outside the window must stay exactly as they were.

Return the new integer after the button press. Build one mask that has ones exactly in positions lo to hi and combine it with n using XOR. Every call takes O(1) time and O(1) extra space. The result always fits in a signed 32-bit integer because only bits 0 to 30 are ever touched.

Example 1

Input:
n = 10, lo = 1, hi = 2
Output:
12
Explanation:

10 is 1010; flipping bits 1 and 2 gives 1100, which is 12.

Example 2

Input:
n = 0, lo = 0, hi = 3
Output:
15
Explanation:

Flipping bits 0..3 of zero turns on four switches, giving 15.

Constraints

0 ≤ n ≤ 231 - 1; 0 ≤ lo ≤ hi ≤ 30

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(1)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…