Flip One Bit
Position 0 of a binary number is its lowest bit, worth 1; position 1 is worth 2, position 2 is worth 4, and so on.
Return n with the bit at position k flipped: a 0 there becomes 1, and a 1 becomes 0. All other bits stay as they are.
Example 1
n 10
k 0
returns 11
10 is 1010. Flipping position 0 gives 1011, which is 11.
Example 2
n 10
k 1
returns 8
10 is 1010. Flipping position 1 gives 1000, which is 8.
Example 3
n 5
k 4
returns 21
Flipping a bit above the number switches it on: 5 + 16.
Constraints
0 <= n <= 10**90 <= k <= 29
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Bits problems
- Gray Code SequenceBeginner
- How Many Bits LongBeginner
- Keep the Low BitsBeginner
- Lowest Set BitBeginner
- Parity BitBeginner
- Read One BitBeginner
- Read a Binary StringBeginner
- Set Bit PositionsBeginner