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
.
Example
1
2
3
Input: x = 0b0111, pos = 3
Output: 0b1111
Explanation: toggle the left-most bit (position 3) using a single-bit mask.
Similar Problems
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 ^ mask
and return it.
Validate pos
if needed (e.g., ensure pos >= 0
and within the word width).
Edge cases:
If pos
is outside the intended bit-width, either normalize (mask pos
) or raise/handle as an error depending on caller expectations.
Code#
Cpp
Go
Java
Python
1
2
3
4
5
6
7
class Solution {
public :
unsigned int toggleBit(unsigned int x, unsigned pos) {
unsigned int mask = 1u << pos;
return x ^ mask;
}
};
1
2
3
4
5
6
package main
func toggleBit (x uint32 , pos uint ) uint32 {
mask := uint32(1 ) << pos
return x ^ mask
}
1
2
3
4
5
6
class Solution {
public int toggleBit (int x, int pos) {
int mask = 1 << pos;
return x ^ mask;
}
}
1
2
3
4
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#
Cpp
Go
Java
Python
1
2
3
4
5
6
7
8
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);
}
};
1
2
3
4
5
6
7
8
9
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 )
}
1
2
3
4
5
6
7
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);
}
}
1
2
3
4
5
6
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
.