Problem#
Given an integer x
and a zero-based bit index pos
, clear (turn off) the bit at pos
without affecting other bits and return the result. If the bit is already 0
, the value should remain unchanged.
Examples#
Example 1#
1
2
3
Input: x = 0b1100 , pos = 3
Output: 0b0100
Explanation: clear bit 3 ( value 8 ) from 12 -> 4.
Solution#
Method 1 — Mask-and-AND: x & ~(1 << pos)
(recommended)#
Intuition#
Create a mask that has a 0
at pos
and 1
s elsewhere, then AND it with x
. That clears the target bit while preserving all other bits.
Approach#
Compute mask = ~(1 << pos)
.
Return x & mask
.
In languages with signed integers, consider masking to the intended word width (e.g., & 0xFFFFFFFF
) if necessary.
Code#
Cpp
Go
Java
Python
1
2
3
4
5
6
7
class Solution {
public :
unsigned int clearBit(unsigned int x, unsigned pos) {
unsigned int mask = ~ (1u << pos);
return x & mask;
}
};
1
2
3
4
5
6
package main
func clearBit (x uint32 , pos uint ) uint32 {
mask := ^(uint32(1 ) << pos )
return x & mask
}
1
2
3
4
5
6
class Solution {
public int clearBit (int x, int pos) {
int mask = ~ (1 << pos);
return x & mask;
}
}
1
2
3
4
class Solution :
def clear_bit (self, x: int, pos: int) -> int:
mask = ~ (1 << pos)
return x & mask
Complexity#
⏰ Time complexity: O(1)
, constant-time bit operations.
🧺 Space complexity: O(1)
.
Method 2 — Conditional clear (alternate)#
Intuition#
Optionally check whether the bit at pos
is set; if so, clear it explicitly using the mask. This avoids a write in some systems if the bit is already 0
.
Approach#
If ((x >> pos) & 1) == 1
, return x & ~(1 << pos)
; otherwise return x
.
Code#
Cpp
Go
Java
Python
1
2
3
4
5
6
7
class Solution {
public :
unsigned int clearBitConditional(unsigned int x, unsigned pos) {
if (((x >> pos) & 1u ) == 1u ) return x & ~ (1u << pos);
return x;
}
};
1
2
3
4
5
6
7
8
package main
func clearBitConditional (x uint32 , pos uint ) uint32 {
if ((x >> pos ) & 1 ) == 1 {
return x & ^(uint32(1 ) << pos )
}
return x
}
1
2
3
4
5
6
class Solution {
public int clearBitConditional (int x, int pos) {
if (((x >> pos) & 1) == 1) return x & ~ (1 << pos);
return x;
}
}
1
2
3
4
5
class Solution :
def clear_bit_conditional (self, x: int, pos: int) -> int:
if ((x >> pos) & 1 ) == 1 :
return x & ~ (1 << pos)
return x
Complexity#
⏰ Time complexity: O(1)
.
🧺 Space complexity: O(1)
.
Applications#
Use these primitives to maintain packed boolean flags (bitsets) for low-memory state tracking.
Combine with bit masks for toggling, setting, or querying bits to implement efficient bit-packed data structures.
Notes
The original article and examples were preserved conceptually; code examples use small clear variable names and language-idiomatic styles.