Clear the n-th bit
EasyUpdated: Sep 18, 2025
Problem
Given an integer x and a zero-based index n, clear (unset) the n-th bit of x and return the resulting value. Clearing sets the n-th bit to 0 while leaving all other bits unchanged.
Examples
Example 1
Input: x = 0b01111111 (127), n = 4
Output: 0b01101111
Explanation: the bit at position 4 is cleared.
Solution
Method 1 — Mask-and-AND using ~(1 << n) (recommended)
Intuition
Create a mask that has all bits 1 except a 0 at position n by computing ~(1 << n). AND-ing x with this mask clears the n-th bit while preserving other bits.
Approach
- Compute
mask = ~(1 << n). - Return
x & mask. - In languages where integers are signed or have implementation-defined widths, mask results to the intended unsigned width when necessary (e.g.,
& 0xFFFFFFFF).
Code
C++
class Solution {
public:
unsigned int unsetNthBit(unsigned int x, unsigned int n) {
unsigned int mask = ~(1u << n);
return x & mask;
}
};
Go
package main
func unsetNthBit(x uint32, n uint) uint32 {
mask := ^(uint32(1) << n)
return x & mask
}
Java
class Solution {
public int unsetNthBit(int x, int n) {
int mask = ~(1 << n);
return x & mask;
}
}
Python
class Solution:
def unset_nth_bit(self, x: int, n: int) -> int:
mask = ~(1 << n)
return x & mask
Complexity
- ⏰ Time complexity:
O(1), constant-time bit operations. - 🧺 Space complexity:
O(1).
Method 2 — Conditional clear (alternate)
Intuition
Optionally test whether the n-th bit is set; clear it only if it's 1. This avoids an unnecessary write in some contexts and makes intent explicit.
Approach
- Check
b = (x >> n) & 1. - If
b == 1, returnx & ~(1 << n), else returnx.
Code
C++
class Solution {
public:
unsigned int unsetNthBitConditional(unsigned int x, unsigned int n) {
if (((x >> n) & 1u) == 1u) return x & ~(1u << n);
return x;
}
};
Go
package main
func unsetNthBitConditional(x uint32, n uint) uint32 {
if ((x >> n) & 1) == 1 {
return x & ^(uint32(1) << n)
}
return x
}
Java
class Solution {
public int unsetNthBitConditional(int x, int n) {
if (((x >> n) & 1) == 1) return x & ~(1 << n);
return x;
}
}
Python
class Solution:
def unset_nth_bit_conditional(self, x: int, n: int) -> int:
if ((x >> n) & 1) == 1:
return x & ~(1 << n)
return x
Complexity
- ⏰ Time complexity:
O(1). - 🧺 Space complexity:
O(1).
Notes
- The mask
~(1 << n)turns on all bits except then-th, makingx & maska concise way to clear the target bit. This is the same primitive shown in many bit-hack collections.