

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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,
#include <iostream> using namespace std; void findKBitVal(int n, int k){ cout<< ((n & (1 << (k - 1))) >> (k - 1)); } int main(){ int n = 29, k = 4; cout<<"The value of kth bit in binary of the number is "; findKBitVal(n, k); return 0; }
Output
The value of kth bit in binary of the number is 1
- Related Questions & Answers
- Find k-th bit in a binary string created by repeated invert and append operations in C++
- Program to find Kth bit in n-th binary string using Python
- Position of the K-th set bit in a number in C++
- Find m-th smallest value in k sorted arrays in C++
- Program to find k-th largest XOR coordinate value in Python
- Check whether K-th bit is set or nots in Python
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Find k’th character of decrypted string in C++
- Find K-th Smallest Pair Distance in C++
- Array Representation Of Binary Heap
- Golang program to turn off the k’th bit in a number.
- Golang Program to turn on the k’th bit in a number.
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Find k-th character of decrypted string - Set – 2 in C++
Advertisements