3. Check if K-th Bit is Set

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

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

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

Solving Approach

AND with single shifted 1 bit. All other bits become 0 because AND with 0 is always zero. This either results in all zeros or a single 1 bit in the right position. Shift it back right to format the answer as either 0 or 1 respectively

 

 

Was this helpful?
Upvote
Downvote