easy +8 pts

Check kth bit

Determine if the k-th bit of an integer is set using bitwise operations.

Write a function `is_kth_bit_set(n: int, k: int) -> bool` that returns `True` if the `k`-th bit of the non-negative integer `n` is set (i.e., equals 1), and `False` otherwise. Bits are numbered from 0, starting at the least significant bit (the rightmost bit). For example, `n = 5` is binary `101`, so bit 0 is 1, bit 1 is 0, bit 2 is 1. Constraints: - `n` is a non-negative integer (`0 <= n <= 10^9`). - `k` is a non-negative integer (`0 <= k <= 30`). - Do not use string conversion or built-in bit-counting functions like `bin()` or `bit_length()`. You may use bitwise operators (`&`, `|`, `<<`, `>>`, `^`). Your solution should work in O(1) time and O(1) space.

Constraints

0 <= n <= 10^9, 0 <= k <= 30. Target O(1) time and O(1) space.

Example

>>> is_kth_bit_set(5, 0)
True
>>> is_kth_bit_set(5, 1)
False
>>> is_kth_bit_set(5, 2)
True
>>> is_kth_bit_set(0, 3)
False
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use left shift to create a mask with a 1 at the k-th position.
Apply the bitwise AND operator between n and the mask.
The result is non-zero exactly when the k-th bit is set.
Remember that bit indexing starts from 0 at the least significant bit.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.