All submissions

Check if K-th Bit is Set

Code

#include <stdio.h>

int isKthBitSet(int n, int k) {
    // Write your code here
    int out = n & (0x01 << k);
    return out >> k;
}

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

Solving Approach

 

First, make a single bit mask (0x01 to start) that is then shifted over 'k' times to the left to target the specified bit. Then AND it with 'n' to see if that bit it set or not in a new variable. Lastly, shift the new variable back over 'k' times to the right to obtain a 0 or 1 output, otherwise you will output a number equal to the bit position only or 0.

 

Loading...

Input

8 3

Expected Output

1