Check if K-th Bit is Set

durgaramprasadtula
durgaramprasadtula

Code

#include <stdio.h>

int isKthBitSet(int n, int k) {
    return (n & (1 << k)) ? 1 : 0;
}

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

Solving Approach

  1. Read inputs: N and K
  2. Use bitwise AND to check if the K-th bit is set:
    • Expression: N & (1 << K)
    • If result is non-zero → bit is set (1)
    • If result is zero → bit is not set (0)
  3. Print result

 

 

Loading...

Input

8 3

Expected Output

1