
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Kth Least Significant Bit of a Number in C++
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
#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
Advertisements