Check if K-th Bit is Set

Code

#include <stdio.h>

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

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

Solving Approach

I just right shifted the original value i.e. n by k (that is the bit position that's to be checked) and performed AND operation with 1. 
If AND result is 1, then the bit is set, otherwise it is not set.

 

Upvote
Downvote
Loading...

Input

8 3

Expected Output

1