check whether kth bit is 1

To check whether the kth bit is 1 in C++, you can use bitwise operations. Here's how you can do it:

  1. Start by defining the number you want to check as an unsigned integer.
  2. Shift the number k-1 places to the right using the right shift operator (>>).
  3. Perform a bitwise AND operation with the result of the right shift and 1.
  4. If the result of the bitwise AND operation is 1, then the kth bit is 1. Otherwise, it is 0.

Here's the code that demonstrates this process:

bool isKthBitSet(unsigned int num, int k) {
    unsigned int mask = 1 << (k-1);
    return (num & mask) != 0;
}

In this code, the function isKthBitSet takes two parameters: num, which is the number you want to check, and k, which is the position of the bit you want to check.

Let's break down the code step by step:

  1. We start by creating a mask using the left shift operator (<<). The mask has a 1 at the kth position and 0s everywhere else. By shifting 1 k-1 places to the left, we ensure that the kth bit is set to 1 in the mask.
  2. Next, we perform a bitwise AND operation (&) between the number and the mask. This operation will preserve only the kth bit in the number and set all other bits to 0.
  3. Finally, we check if the result of the bitwise AND operation is not equal to 0. If it is not equal to 0, it means that the kth bit is 1, and we return true. Otherwise, we return false.

That's it! You can now use the isKthBitSet function to check whether the kth bit is 1 in a given number.