Check if K-th Bit is Set

Code

#include <stdio.h>

int isKthBitSet(int n, int k) {
    return (n & (1<<k)) >> k ;
}

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

Solving Approach

First, we have to bitwise & n against the Kth bit. Then, since doing that returns the a binary, we shift it to the right by K to get whether the Kth bit is actually set or not. And since binary can only be either 1 or 0, that means we can immediately output this value.  

 

 

Upvote
Downvote
Loading...

Input

8 3

Expected Output

1