Set the n-th bit
EasyUpdated: Sep 20, 2025
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
Input: x = 120 (0b01111000), n = 2
Output: 124 (0b01111100)
Example 2
Input: x = -120 (two's complement), n = 6
Output: -56 (0b11001000 as signed -56)
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
nis within a reasonable range for the target word size (e.g.,0 <= n < 32for 32-bit integers). - Compute
mask = 1 << nand returnans = x | mask.
Edge cases:
- Large
nmay overflow shift width in some languages; prefer using unsigned types or guardn. - Negative
xworks correctly in two's complement representation for bitwise operations.
Code
C++
class Solution {
public:
int setNthBit(int x, int n) {
return x | (1 << n);
}
};
Go
package main
func setNthBit(x int32, n uint) int32 {
return x | (1 << n)
}
Java
class Solution {
public int setNthBit(int x, int n) {
return x | (1 << n);
}
}
Python
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
nis outside the allowed range, returnxor raise an error. - Otherwise compute
mask = 1 << nand returnx | mask.
Code
C++
class Solution {
public:
int setNthBit(int x, int n) {
if (n < 0 || n >= 32) return x; // guard for 32-bit
return x | (1 << n);
}
};
Go
package main
func setNthBit(x int32, n int) int32 {
if n < 0 || n >= 32 {
return x
}
return x | (1 << uint(n))
}
Java
class Solution {
public int setNthBit(int x, int n) {
if (n < 0 || n >= 32) return x;
return x | (1 << n);
}
}
Python
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).