Check If Kth Bit Is Set/Unset
Understand how to determine if the kth bit of an integer is set or unset by using the bitwise left shift and AND operators. This lesson helps you implement an optimal O(1) time solution to check bits in binary representations, a key skill for bit manipulation in coding interviews.
Introduction
In this question, input a number and check if the bit is set or not.
Problem statement
Given two positive integers n and k check whether the bit at position k, from the right in the binary representation of n, is set 1 or unset 0.
Input: n = 5, k = 1
Output: true
Input: n = 10, k = 2
Output: true
Input: n = 10, k = 1
Output: false
Algorithm
- If
n == 0return;