Check if K-th Bit is Set

Code

#include <stdio.h>

int isKthBitSet(int n, int k) {
    // Write your code here
    if (n & (1<<k)){
        return 1;
    }
    else return 0;

}

int main() {
    int n, k;
    scanf("%d %d", &n, &k);
    printf("%d", isKthBitSet(n, k));
    return 0;
}

Solving Approach

 

✅ Check if K-th Bit is Set — Small & Compact Approach

1️⃣ Create a mask for K-th bit

1 << k

This makes a number where only the K-th bit is 1.

2️⃣ Use AND to isolate that bit

n & (1 << k)
  • If result ≠ 0 → bit is set (1)
  • If result = 0 → bit is not set (0)

3️⃣ Return the result as 0 or 1

Best compact form:

(n >> k) & 1

💡 Final One-Line Logic

return (n >> k) & 1;

✔ Shifts K-th bit to LSB
✔ Masks only that bit
✔ Directly gives 0 or 1
✔ Clean & interview-ready

 

Upvote
Downvote
Loading...

Input

8 3

Expected Output

1