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) {
    const int mask = 1 << k;
    return (n & mask) ? 1 : 0;
}

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

Solving Approach

The problem here is to get the right mask. We could pre-compute this but for a variable it also makes sense to shift out based on the bit position. Once we isolate the correct bit, we can & with the value. This would allow the value to become zero if it wasn't set and positive otherwise. In that way it can be treated as a simple condition and return 0 or 1.

 

 

Was this helpful?
Upvote
Downvote