Toggle a specified bit in a bit string without effecting other bits
EasyUpdated: Sep 29, 2025
Problem
Given an integer x (interpreted as a bit string) and a zero-based bit index pos, toggle the bit at position pos without affecting other bits and return the resulting value. Toggling flips the bit: 0 -> 1 and 1 -> 0.
Examples
Example 1
Input: x = 0b0111, pos = 3
Output: 0b1111
Explanation: toggle the left-most bit (position 3) using a single-bit mask.
Solution
Method 1 — XOR with a single-bit mask (recommended)
Intuition
XORing a bit with 1 flips it and XORing with 0 leaves it unchanged. Build a mask that has a 1 only at pos and XOR it with x to toggle that bit while leaving others intact.
Approach
- Create a mask with
mask = 1 << pos. - Compute
result = x ^ maskand return it. - Validate
posif needed (e.g., ensurepos >= 0and within the word width).
Edge cases:
- If
posis outside the intended bit-width, either normalize (maskpos) or raise/handle as an error depending on caller expectations.
Code
C++
class Solution {
public:
unsigned int toggleBit(unsigned int x, unsigned pos) {
unsigned int mask = 1u << pos;
return x ^ mask;
}
};
Go
package main
func toggleBit(x uint32, pos uint) uint32 {
mask := uint32(1) << pos
return x ^ mask
}
Java
class Solution {
public int toggleBit(int x, int pos) {
int mask = 1 << pos;
return x ^ mask;
}
}
Python
class Solution:
def toggle_bit(self, x: int, pos: int) -> int:
mask = 1 << pos
return x ^ mask
Complexity
- ⏰ Time complexity:
O(1), one bit-shift and one XOR. - 🧺 Space complexity:
O(1).
Method 2 — Conditional set/clear (explicit)
Intuition
Read the current bit at pos. If it is 1, clear it; if it is 0, set it. This uses mask and bitwise set/clear operations explicitly rather than XOR.
Approach
- Extract
b = (x >> pos) & 1. - If
b == 1, clear the bit:result = x & ~(1 << pos). - Else set the bit:
result = x | (1 << pos).
Code
C++
class Solution {
public:
unsigned int toggleBitExplicit(unsigned int x, unsigned pos) {
unsigned int b = (x >> pos) & 1u;
if (b == 1u) return x & ~(1u << pos);
return x | (1u << pos);
}
};
Go
package main
func toggleBitExplicit(x uint32, pos uint) uint32 {
b := (x >> pos) & 1
if b == 1 {
return x & ^(uint32(1) << pos)
}
return x | (uint32(1) << pos)
}
Java
class Solution {
public int toggleBitExplicit(int x, int pos) {
int b = (x >> pos) & 1;
if (b == 1) return x & ~(1 << pos);
return x | (1 << pos);
}
}
Python
class Solution:
def toggle_bit_explicit(self, x: int, pos: int) -> int:
b = (x >> pos) & 1
if b == 1:
return x & ~(1 << pos)
return x | (1 << pos)
Complexity
- ⏰ Time complexity:
O(1). - 🧺 Space complexity:
O(1).
Notes
- This is a basic bit-manipulation primitive. There is no exact LeetCode problem with this precise title — it's a commonly used operation in many bitwise tasks.
- Original reference kept in
source_links.