Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Find value of k-th bit in binary representation in C++
In this problem, we are given two values n and k. Our task is to find value of k-th bit in binary representation.
Let's take an example to understand the problem,
Input : n= 5, k = 2 Output : 0
Explanation −
Binary of 5 = 0101 Second LSB bit is 0.
Solution Approach
A solution to the problem is by performing bitwise AND of the binary conversion of the number N with a number with all bits unset and one bit set which is at kth position, to get the result.
Example
Program to illustrate the working of our solution,
#includeusing namespace std; void findKBitVal(int n, int k){ cout> (k - 1)); } int main(){ int n = 29, k = 4; cout Output
The value of kth bit in binary of the number is 1
Advertisements
