Flip a specific bit in an integer
Company: Box
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: Medium
Interview Round: Onsite
Quick Answer: This question evaluates a candidate's understanding of bitwise operations and low-level integer manipulation, along with the ability to reason about the time and space complexity of bit-level operations.
Constraints
- 0 <= num (non-negative integer)
- 0 <= p (zero-based bit position)
- Flipping a bit at a position beyond num's highest set bit simply sets that bit to 1.
- Python integers are arbitrary-precision, so very large p values are handled natively.
Examples
Input: (5, 0)
Expected Output: 4
Explanation: 5 is 101. Bit 0 is 1, so it clears to 0: 100 = 4.
Input: (5, 1)
Expected Output: 7
Explanation: 5 is 101. Bit 1 is 0, so it sets to 1: 111 = 7.
Input: (0, 0)
Expected Output: 1
Explanation: 0 is 0. Flipping bit 0 sets it: 1.
Input: (8, 3)
Expected Output: 0
Explanation: 8 is 1000. Bit 3 is the only set bit; flipping it clears the number to 0.
Input: (0, 31)
Expected Output: 2147483648
Explanation: Flipping bit 31 of 0 yields 2^31 = 2147483648, showing high-bit positions work.
Input: (1023, 5)
Expected Output: 991
Explanation: 1023 is 1111111111. Clearing bit 5 (value 32) gives 1023 - 32 = 991.
Input: (7, 10)
Expected Output: 1031
Explanation: 7 is 111. Bit 10 is beyond the top set bit, so flipping it just adds 2^10 = 1024: 7 + 1024 = 1031.
Hints
- Which bitwise operator toggles a bit: AND, OR, or XOR? Recall that x ^ 1 = NOT x and x ^ 0 = x.
- Build a mask with a single 1 at position p using a left shift: 1 << p.
- XOR the number with that mask: num ^ (1 << p). This flips only the targeted bit and leaves every other bit untouched, in O(1) time and space.