All submissions

Check if K-th Bit is Set

Code

#include <stdio.h>


int isKthBitSet(int n, int k) {
    if (n & (1U << k)) {
        return 1;
    }

    return 0;
}

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

The goal is to determine whether the k-th bit (0-indexed from the right) of a given integer n is set (i.e., equals 1).

1. Left shift the number 1 by k positions to create a bitmask that has only the k-th bit set.
  Example: If k = 2, then (1 << k) = 00000100 in binary.

2. Perform a bitwise AND between n and the bitmask.
  - If the result is non-zero, it means the k-th bit in n is set.
  - If the result is zero, it means the k-th bit is not set.

3. Return 1 if the bit is set, otherwise return 0.

 

 

 

Loading...

Input

8 3

Expected Output

1