Toggle a Range of Bits
Treat n as a 32 bit unsigned value with bit 0 as its lowest bit. Flip every bit whose position is between lo and hi inclusive (a 0 turns into a 1, a 1 turns into a 0) and leave all other bits exactly as they were. Return the new value as a non-negative integer. Since hi may be 31, the answer can reach 2**32 - 1.
Example 1
n 10
lo 0
hi 1
returns 9
10 is 1010; flipping bits 0 and 1 gives 1001, which is 9.
Example 2
n 5
lo 1
hi 2
returns 3
5 is 101; flipping bits 1 and 2 gives 011, which is 3.
Constraints
0 <= n < 2**310 <= lo <= hi <= 31
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Bits problems
- XOR Up To NEasy
- Bitwise OR of a RangeMedium
- Different ORs of StretchesMedium
- Differing Bits Over All PairsMedium
- Flips to Make OR EqualMedium
- Insert a Bit FieldMedium
- Longest Pair With No Shared LetterMedium
- Next Gray CodeMedium