Problem#
Given an integer x and a bit index n (0-based, least significant bit is n=0), set the n-th bit of x and return the result.
Examples#
Example 1#
1
2
| Input: x = 120 (0b01111000), n = 2
Output: 124 (0b01111100)
|
Example 2#
1
2
| Input: x = -120 (two's complement), n = 6
Output: -56 (0b11001000 as signed -56)
|
Similar Problems
Solution#
Method 1 — Bit mask and OR (x | (1 << n)) (recommended)#
Intuition#
Create a mask with only the n-th bit set (1 << n) and OR it with x. OR sets that bit to 1 while leaving other bits unchanged.
Approach#
- Validate
n is within a reasonable range for the target word size (e.g., 0 <= n < 32 for 32-bit integers). - Compute
mask = 1 << n and return ans = x | mask.
Edge cases:
- Large
n may overflow shift width in some languages; prefer using unsigned types or guard n. - Negative
x works correctly in two’s complement representation for bitwise operations.
Code#
1
2
3
4
5
6
| class Solution {
public:
int setNthBit(int x, int n) {
return x | (1 << n);
}
};
|
1
2
3
4
5
| package main
func setNthBit(x int32, n uint) int32 {
return x | (1 << n)
}
|
1
2
3
4
5
| class Solution {
public int setNthBit(int x, int n) {
return x | (1 << n);
}
}
|
1
2
3
| class Solution:
def set_nth_bit(self, x: int, n: int) -> int:
return x | (1 << n)
|
Complexity#
- ⏰ Time complexity:
O(1), single shift and OR. - 🧺 Space complexity:
O(1).
Method 2 — Guarded set (check then set)#
Intuition#
If you want to avoid undefined behavior for large n in languages where shifting out-of-range is undefined, perform a guard check before shifting.
Approach#
- If
n is outside the allowed range, return x or raise an error. - Otherwise compute
mask = 1 << n and return x | mask.
Code#
1
2
3
4
5
6
7
| class Solution {
public:
int setNthBit(int x, int n) {
if (n < 0 || n >= 32) return x; // guard for 32-bit
return x | (1 << n);
}
};
|
1
2
3
4
5
6
7
8
| package main
func setNthBit(x int32, n int) int32 {
if n < 0 || n >= 32 {
return x
}
return x | (1 << uint(n))
}
|
1
2
3
4
5
6
| class Solution {
public int setNthBit(int x, int n) {
if (n < 0 || n >= 32) return x;
return x | (1 << n);
}
}
|
1
2
3
4
5
| class Solution:
def set_nth_bit(self, x: int, n: int) -> int:
if n < 0 or n >= 32:
return x
return x | (1 << n)
|
Complexity#
- ⏰ Time complexity:
O(1). - 🧺 Space complexity:
O(1).