C++ Program to Find the nth Bit of Number (Bit Masking)

C++ Program to Find the nth Bit of Number (Bit Masking)

Sometimes interviewers also twist the question and ask you to check if the nth bit is set or not. You have to follow the same approach.

Algorithm and approach:

  1. Left shift 1 ‘n’ times and store it in a variable.
  2. Bitwise AND the variable with the number.
  3. If the output is zero, the ith bit is zero else the nth bit is one. 

C++ Code:

#include <iostream>
using namespace std;
 
int main()
{
    //Question is find the ith bit of number.
 
   //number is 15
   int num = 15;

   //i is the required bit position   
   int n=6;

   int mask = 1<<n;

   int result= num & mask;

   if(result == 0) cout<<"The nth bit of the number is zero.";

   else cout<<"The nth bit of the number is one.";

    return 0;
}

Output:

The nth bit of the number is zero.

This approach is also called as bit masking.

This is all about the C++ program to find the nth bit of number. You can implement the same logic in any other programming language like C, Python.

To improve your bit manipulation skills, check the set of bit manipulation interview questions in data structure coding questions.

Leave a Reply

Your email address will not be published. Required fields are marked *