Check whether kth bit is set or not


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:


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


Intuition

In binary, each bit represents a power of two. To check if the k-th bit is set, we:

  1. Create a bitmask with 1 at the k-th position using left shift: 1 << k.

  2. 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


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

Input: n = 4, k = 0


Conclusion

This problem is a fundamental bit manipulation exercise often used to:

It’s a constant-time, zero-extra-space solution and helps form the basis for more complex bit-based algorithms.