在二進位制表示中查詢在 C++ 中的第 k 位
在這個問題中,我們獲得了兩個值 n 和 k。我們的任務是查詢二進位制表示中第 k 位的值。
讓我們舉個例子來理解這個問題,
Input : n= 5, k = 2 Output : 0
說明 −
Binary of 5 = 0101 Second LSB bit is 0.
解決方案方法
問題的解決方案是將數字 N 的二進位制轉換與一個所有位未設定且一位設定為第 k 位的數字執行按位 AND,以獲得結果。
示例
展示我們的解決方案工作原理的程式,
#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;
}輸出
The value of kth bit in binary of the number is 1
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP