KatInterview

Invert Bit at Specific Index

Math & Bit ManipulationModel answer
EasyModel answerMath & Bit Manipulationmath-bitsbit-manipulationmath

Last 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 (binary 1010), p = 1
  • Output: 8 (binary 1000)
  • Explanation: Bit index 1 is currently 1. Flipping it changes the binary representation to 1000 (decimal 8).

Example 2:

  • Input: num = 10 (binary 1010), p = 0
  • Output: 11 (binary 1011)
  • Explanation: Bit index 0 is currently 0. Flipping it changes the binary representation to 1011 (decimal 11).

Example 3:

  • Input: num = 5 (binary 101), p = 10
  • Output: 1029 (binary 10000000101)
  • Explanation: Bit index 10 is implicitly 0. Flipping it sets it to 1, adding $2^{10} = 1024$ to 5.

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.