Invert Bit at Specific Index
Math & Bit ManipulationModel answerLast updated
Invert the bit at a given index in a non-negative integer using bitwise operations.
Write a function that takes a non-negative integer num and a zero-based bit index p (where position 0 corresponds to the least significant bit), and returns the number with the bit at index p inverted (toggled from 0 to 1 or 1 to 0).
All other bits must remain untouched. If p is greater than the highest set bit in num, assume the missing bits are 0 and toggle position p to 1.
Input
num(integer): A non-negative integer ($0 \le \text{num}$).p(integer): A zero-based bit position ($0 \le p$).
Output
- Returns the resulting integer after flipping bit
p.
Examples
Example 1:
- Input:
num = 10(binary1010),p = 1 - Output:
8(binary1000) - Explanation: Bit index 1 is currently
1. Flipping it changes the binary representation to1000(decimal8).
Example 2:
- Input:
num = 10(binary1010),p = 0 - Output:
11(binary1011) - Explanation: Bit index 0 is currently
0. Flipping it changes the binary representation to1011(decimal11).
Example 3:
- Input:
num = 5(binary101),p = 10 - Output:
1029(binary10000000101) - Explanation: Bit index 10 is implicitly
0. Flipping it sets it to1, adding $2^{10} = 1024$ to5.
Hints
Hint 1
Recall how bitwise XOR (^) operates when combined with 0 versus 1.
Hint 2
Think about how to create a bitmask that has a single bit set at position `p`.
Hint 3
Avoid using conditional checks (`if/else`) to check the current value of bit `p`; a single bitwise operation can toggle it directly.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach Walkthrough
To toggle a single bit without modifying any other bits, we leverage the bitwise XOR (^) operation combined with a bitmask.
- Construct a Mask: Shift the value
1left byppositions (1 << p). This produces a number where only bitpis set to1and all other positions are0. - Apply Bitwise XOR: Compute
num ^ mask.
Why XOR Works
The truth table for XOR (^) on a bit a with a mask bit b shows:
- $a \oplus 0 = a$ (The original bit is preserved).
- $a \oplus 1 = \neg a$ (The original bit is inverted).
Because every bit in our mask is 0 except at position p, performing num ^ (1 << p) leaves every bit unchanged except for bit p, which gets flipped automatically regardless of whether its initial value was 0 or 1.
Python Code
def flip_bit(num: int, p: int) -> int:
"""
Inverts the bit at index p in the integer num.
Args:
num: Non-negative integer.
p: Zero-based bit index (0 is LSB).
Returns:
The integer result after flipping bit p.
"""
if num < 0 or p < 0:
raise ValueError("Inputs num and p must be non-negative.")
return num ^ (1 << p)
Complexity Analysis
- Time Complexity: $\mathcal{O}(1)$ for fixed-width integers (e.g., 32-bit or 64-bit standard types). In languages with arbitrary-precision integers (like Python), bitwise shifts and XOR take time proportional to the bit length, $\mathcal{O}(\max(p, \text{num.bit_length()}))$, which is effectively constant for standard numeric bounds.
- Space Complexity: $\mathcal{O}(1)$ auxiliary space as we only store a single mask integer.
Key Follow-ups & Related Bit Operations
Interviewers frequently follow up by asking how to perform other single-bit modifications. Knowing the standard bitwise operations for single bits is essential:
| Goal | Expression | Behavior on Bit p |
|---|---|---|
| Check / Read | (num >> p) & 1 | Returns 1 if set, 0 otherwise. |
| Set (Force to 1) | `num | (1 << p)` |
| Clear (Force to 0) | num & ~(1 << p) | Sets bit p to 0; retains value if already 0. |
| Toggle / Flip | num ^ (1 << p) | Inverts bit p (0 $\rightarrow$ 1, 1 $\rightarrow$ 0). |
Common Pitfalls & Edge Cases
- Arithmetic vs. Bitwise Operations: Attempting to add or subtract
(1 << p)directly (e.g.,num + (1 << p)) fails if bitpis already1, causing carries into higher bit positions. - Global Bit Inversion (
~): Using bitwise NOT (~num) flips all bits in the integer rather than targeting only positionp. - Fixed-Width Overflow (C++/Java): Shifting a standard 32-bit
signed intby 31 or more can lead to undefined behavior or negative values. In fixed-width languages, ensure1ULL << p(or 64-bit unsigned types) is used when working with higher indices.