Problem#
Given a 32-bit integer num
, determine whether the i-th
bit (counting from 0 at the least-significant bit) is set (i.e., equals 1
).
Follow up#
Can you check if a target bit is set without affecting other bits?
Examples#
Example 1#
1
2
3
Input: num = 20 , i = 2
Output: true
Explanation: 20 = 10100 ₂ ; bit at index 2 is 1.
Example 2#
1
2
3
Input: num = 20 , i = 3
Output: false
Explanation: 20 = 10100 ₂ ; bit at index 3 is 0.
Solution#
We can test the i
th bit with a mask that has only that bit set: 1 << i
. Bitwise AND with num
preserves that bit; a non-zero result means the bit is set.
Method 1 – Bit Mask Check#
Intuition#
Create a mask = 1 << i
which has only the i
th bit set. num & mask
will be non-zero iff num
’s i
th bit is 1
.
Approach#
Validate input: i
should be non-negative and less than the integer width (implementation-dependent).
Compute mask = 1 << i
.
Return (num & mask) != 0
.
Edge cases#
If i
is out of range for the integer type, use a wider type (e.g., 64-bit) or return false/raise an error depending on requirements.
Negative num
(two’s complement) is fine — the bitwise test still inspects the bit pattern.
Note#
This already answers the follow up as well, as we don’t modify the input number.
Code#
Cpp
Go
Java
Python
1
2
3
4
5
6
7
8
class Solution {
public :
bool isNthBitSet(unsigned int num, unsigned int i) {
if (i >= sizeof (num) * 8 ) return false;
unsigned int mask = 1u << i;
return (num & mask) != 0u ;
}
};
1
2
3
4
5
6
package main
func isNthBitSet (num uint , i uint ) bool {
mask := uint(1 ) << i
return (num & mask ) != 0
}
1
2
3
4
5
6
7
class Solution {
public boolean isNthBitSet (int num, int i) {
if (i < 0 || i >= Integer.SIZE ) return false ;
int mask = 1 << i;
return (num & mask) != 0;
}
}
1
2
3
4
5
6
class Solution :
def is_nth_bit_set (self, num: int, i: int) -> bool:
if i < 0 :
return False
mask: int = 1 << i
return (num & mask) != 0
Complexity#
⏰ Time complexity: O(1)
, a constant number of bit operations.
🧺 Space complexity: O(1)
, constant extra space for the mask.