Check whether kth bit is set or not
Problem Link
Check whether K-th bit is set or not – GFG
Problem Statement
Given a number n and a value k, check whether the k-th bit (0-indexed from the right) in the binary representation of n is set (i.e., is 1) or not.
Return:
-
trueif the bit is set -
falseotherwise
Examples
Example 1:
Input: n = 4, k = 0
Output: false
Explanation: Binary of 4 = 100. 0-th bit (LSB) is 0.
Example 2:
Input: n = 4, k = 2
Output: true
Explanation: Binary of 4 = 100. 2nd bit is 1.
Constraints
-
0 <= n <= 10⁹ -
0 <= k <= 31
Intuition
In binary, each bit represents a power of two. To check if the k-th bit is set, we:
-
Create a bitmask with
1at the k-th position using left shift:1 << k. -
Use bitwise AND with
n:-
If the result is non-zero, the k-th bit is set.
-
Otherwise, it’s not set.
-
Approach: Bitwise AND with Mask
-
Construct a number with only the k-th bit set:
1 << k. -
Perform:
n & (1 << k)-
If result is non-zero → bit is set.
-
Else → not set.
-
Java Code
class CheckBit {
static boolean checkKthBit(int n, int k) {
int check = 1 << k;
return ((n & check) == check);
}
}
Time and Space Complexity
| Metric | Value |
|---|---|
| Time Complexity | O(1) |
| Space Complexity | O(1) |
| Explanation | Only uses bitwise operations, no loops or extra space |
Dry Run
Input: n = 4, k = 2
-
Binary of
n:100 -
Bitmask:
1 << 2 = 100(binary) -
n & (1 << k)=100 & 100=100→ Non-zero → Bit is set →true
Input: n = 4, k = 0
-
Binary of
n:100 -
Bitmask:
1 << 0 = 001(binary) -
n & (1 << 0)=100 & 001=000→ Zero → Bit not set →false
Conclusion
This problem is a fundamental bit manipulation exercise often used to:
-
Teach bitmasking
-
Check understanding of shift operations and binary logic
It’s a constant-time, zero-extra-space solution and helps form the basis for more complex bit-based algorithms.