Check if K-th Bit is Set

Code

#include <stdio.h>

int isKthBitSet(int n, int k) {
    // Left shift 1 by k to create a mask with only the k-th bit set
    int mask = (1 << k);
    
    // Perform bitwise AND operation with n and the mask
    // If the result is non-zero, the k-th bit is set
    if ((n & mask) != 0) {
        return 1; // K-th bit is set
    } else {
        return 0; // K-th bit is not set
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

8 3

Expected Output

1