Last Updated: 20 May, 2022

Check whether K-th bit is set or not

Easy

Problem statement

Given a number ‘N’ and a number ‘K’. Return true if ‘K’th bit of number is set, else return false.


Example:
Input: ‘N’ = 5, ‘K’ = 1

Output: YES

5 in binary can be written as 101 and as we can see a first bit from the right of 5 is set so the answer is 'YES'.

Input Format :

The first line contains two integers ‘N’ and ‘K’ respectively.

Output format :

The only line contains 'YES', if the 'K-th' bit is set, else 'NO'. 

Note :

You don't need to print anything. It has already been taken care of. Just implement the given function.

Approaches

01 Approach

Bitwise and of two bits is true if both bits are high. Left shift operation shifts the bit left by a given number so left shift by K is like 2^K so what we can do is we can shift 1 to the left by k-1 which makes it 2^(K-1) and we do the bitwise and of this with number ‘N’ which result in 2^(K-1) if kth bit is set else it becomes 0. We are reducing K to K-1 because bits start from 0.

 

The steps are as follows:-

  1. Bitwise and of 2 bits is true if both bits are true else it is false.
  2. So we can check the bitwise and of n and 2^(K-1).
  3. Return True if the bitwise and is equal to 2^(K-1) then return True else return False.

02 Approach

In the previous approach we shift 1 to left by (K-1) bits here we will shift N by (K-1) times to the right which will put the K-1 th bit at 0th position and we will check if it is set or not by checking either the number is odd or not.

 

The steps are as follows:-

  1. Check if N right-shifted by (K-1) times is set or not, We can check it by doing bitwise and of it with 1.
  2. If Bitwise and returns 1 return True else return False.