easy +10 pts

Toggle kth Bit

Flip the kth bit of an integer using bitwise XOR.

Write a function `toggle_kth_bit(n: int, k: int) -> int` that takes a non-negative integer `n` and a non-negative integer `k`, and returns the integer obtained by flipping the kth bit of `n` (0-indexed from the least significant bit). The bit is flipped using XOR with a mask that has only that bit set. No bit operations other than XOR and shifts are required. Examples: - `toggle_kth_bit(5, 0)` → 4 (5 is 101, flip bit 0 → 100 = 4) - `toggle_kth_bit(5, 1)` → 7 (5 is 101, flip bit 1 → 111 = 7) - `toggle_kth_bit(0, 0)` → 1 - `toggle_kth_bit(255, 7)` → 127

Constraints

- `0 <= n <= 10^9` - `0 <= k <= 30` - The function must run in O(1) time and O(1) space.

Example

>>> toggle_kth_bit(5, 0)
4
>>> toggle_kth_bit(5, 1)
7
>>> toggle_kth_bit(0, 0)
1
>>> toggle_kth_bit(255, 7)
127
10 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use the XOR operator (^) to flip a single bit.
Create a mask with only the kth bit set using left shift: `1 << k`.
Return `n ^ mask`.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.