Checking the bit at Kth position of integer n


 

 

 

Hello Viewers,

Our problem for the video is How to check the Kth bit of any integer n.


I request you to take some time and think of the solution yourself, 


Before solving the problem we need to understand how ‘and’ operator works.


The bitwise and operator returns one only if both the bits are set to 1.

In all the other cases it returns 0.
Here is the table of bitwise and operator:-


In the table you can clearly see the bitwise and operator returns one only if both flag 

and value are 1.



We can make a simple observation from the table. Whenever the flag is 1, the result

 returned is same as the value.



So if we left shift 1 to kth position and do bitwise and operation with the number 

we will get our result. If our result is 0 the kth bit is 0. Otherwise, it is 1. 



Let’s look at an example,


Here n is 113. And k is 5.


So when we shift 1 to 5th position and do bitwise and operation our result will get a

 non zero value. That means 5th bit is set.



So, The solution to the problem is n & (1<<(k-1)).



I know the problem was very simple. But believe me, by understanding 

simple concepts we will make a background to solve many big complex problems.


You can find the code in the link given in the description.


Friends my aim is to provide maximum variations of coding interview questions and 

explain their solution in a very powerful way.

Please, like the video and subscribe to my channel and press the bell icon to get new video updates. 


#include <iostream> 
using namespace std;

//function to check Kth bit of integer n
bool checkBit(unsigned int n, unsigned int k)
{
int result = n & 1 <<(k - 1);

// if it results to '1' then bit is set,
// else it results to '0' bit is unset
return result;
}

int main()
{
unsigned int n = 10, k = 1;
if (checkBit(n, k))
cout << "bit at position " << k << " is set";
else
cout << "bit at position " << k << " is unset";
return 0;
}

Comments

Popular posts from this blog

Clear right most set bit of an integer n

Advancing through an Array

Partial Sum