![]() |
VOOZH | about |
Given a number n and a bit position k, check if the kth bit of n is set or not. A bit is called set if it is 1 at that position.
Note: Indexing starts with 0 from LSB (least significant bit) side in the binary representation of the number.
Examples:
Input: n = 7, k = 2
Output: true
Explanation: 7 is represented as 111 in binary and bit at position 2 is set.Input: n = 5, k = 1
Output: false
Explanation: 5 is represented as 101 in binary and bit at position 1 is not set.
Table of Content
The idea is to leverage bitwise operations to check if a specific bit is set. Create a number that has only the k-th bit set (by left-shifting 1 by k positions). Then we perform a bitwise AND operation between this number and the given number n. If the result is non-zero, it means the k-th bit in n is set to 1, otherwise it's 0.
true
The idea is to shift the bits of the given number to the right by k positions, which brings the k-th bit to the rightmost position (0th position). Then we perform a bitwise AND operation with 1. If this result is non-zero (meaning the bit is 1), then the k-th bit in the original number was set, otherwise it wasn't.
true