Print Kth least significant bit of a number in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two numbers n and k. Our task is to print the kth least significant bit of the number n.

Let’s take an example to understand the problem

Input: n = 12 , k = 3
Output
1
Explanation:
Let’s see the binary representation of n: 12 = 1100

Now, 3rd least significant bit is 1.

To solve this problem we will use the binary bits of the number. And yield the kth bit of the number. For this, we will use binary shifting of the number and left-shift the number (k-1) times. Now on doing end operation of the shifted number and original number which will give the kth bit’s value.

Example

The below code will show the implementation of our solution

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main() {
   int N = 12, K = 3;
   cout<<K<<"th significant bit of "<<N<<" is : ";
   bool kthLSB = (N & (1 << (K-1)));
   cout<<kthLSB;
   return 0;
}

Output

3th significant bit of 12 is : 1
raja
Published on 03-Feb-2020 10:16:38
Advertisements