Check if K-th Bit is Set

Code

#include <stdio.h>

int isKthBitSet(int n, int k) {
    // Use AND to check the bit index in reg correspond to 1 after shift k bit index
    //If the result after AND equal to the check bit (1 after shift) mean that all the
    //bit in reg after AND will equal to 0 except the bit AND with the check bit, it
    //equal to check bit mean that bit in that position in reg is 1 , otherwise if
    //result is 0 mean that bit in that position in reg is 0 so that it AND with check
    //bit will become 0 too (all other bit become 0 surely) 
    int check_bit = (1 << k);
    int temp;
    temp = n & check_bit;
    if(temp == check_bit){
        return 1;
    }
    else{
        return 0;
    }
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

8 3

Expected Output

1