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

1
2
3
Input: x = 0b01111111 (127), n = 4
Output: 0b01101111
Explanation: the bit at position 4 is cleared.

Solution

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

1
2
3
4
5
6
7
class Solution {
 public:
    unsigned int unsetNthBit(unsigned int x, unsigned int n) {
        unsigned int mask = ~(1u << n);
        return x & mask;
    }
};
1
2
3
4
5
6
package main

func unsetNthBit(x uint32, n uint) uint32 {
        mask := ^(uint32(1) << n)
        return x & mask
}
1
2
3
4
5
6
class Solution {
    public int unsetNthBit(int x, int n) {
        int mask = ~(1 << n);
        return x & mask;
    }
}
1
2
3
4
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, return x & ~(1 << n), else return x.

Code

1
2
3
4
5
6
7
class Solution {
 public:
    unsigned int unsetNthBitConditional(unsigned int x, unsigned int n) {
        if (((x >> n) & 1u) == 1u) return x & ~(1u << n);
        return x;
    }
};
1
2
3
4
5
6
7
8
package main

func unsetNthBitConditional(x uint32, n uint) uint32 {
        if ((x >> n) & 1) == 1 {
                return x & ^(uint32(1) << n)
        }
        return x
}
1
2
3
4
5
6
class Solution {
    public int unsetNthBitConditional(int x, int n) {
        if (((x >> n) & 1) == 1) return x & ~(1 << n);
        return x;
    }
}
1
2
3
4
5
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 the n-th, making x & mask a concise way to clear the target bit. This is the same primitive shown in many bit-hack collections.