Check if K-th Bit is Set

Ternaries to the rescue again :)

#include <stdio.h>

int isKthBitSet(int n, int k) {
    return n & (1 << k) ? 1 : 0;
}

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

Solving Approach

shift one to the bit position, AND it and if it's > 0 it's 1 otherwise 0

 

 

Upvote
Downvote
Loading...

Input

8 3

Expected Output

1