Code

#include <stdio.h>

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

// Method 2
int isKthBitSet(int n, int k) {
    // Write your code here
    n &= (1<<k);
    if (n >= 1){
        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. Think of the AND operator, anything AND-ed with a 0 is zero, the only time that AND will return 1 is when both operators are 1.
  2. Now if we AND any number with 1, we are effectively checking the status of the last bit. To check the other bits we need to left shift the bit 0.
  3. But after left shifting and AND-ing, the result becomes say 0b00010000, which is a value greater than 1. From here use either boolean checking which will require right shifting.
  4. OR simply use greater than operator.

 

 

Upvote
Downvote
Loading...

Input

8 3

Expected Output

1