Check If Kth Bit Is Set/Unset

In this lesson, we try to find a bit in the binary representation of a number at the kth position and check if it is set/un-set. We have already done this, but here we will go over it with the right shift.

Introduction

In this question, input a number and check if the kthk^{th} 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 == 0 return;
  • Initialize k = 1
  • Loop
    • If ((n >> (k - 1)) & 1) == 0 increment the pointer k
    • Else return k

Level up your interview prep. Join Educative to access 80+ hands-on prep courses.