Check if K-th Bit is Set

Code

#include <stdio.h>

int isKthBitSet(int n, int k) {
    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

1.Read the integer n and bit position k

2.shift 1 left by(k-1)positions

3.creates a number where only k-th bit is 1

4.apply bitwise AND(& )between n and the mask

if result 1 set else return 0

print the result in main()

 

 

Upvote
Downvote
Loading...

Input

8 3

Expected Output

1