在 C++ 中列印數字的第 K 個最低有效位
在此問題中,我們給定兩個數字 n 和 k。我們的任務是列印數字 n 的第 k個最低有效位。
讓我們舉個例子來理解問題
Input: n = 12 , k = 3 Output 1 Explanation: Let’s see the binary representation of n: 12 = 1100
現在,第 3 個最低有效位為 1。
要解決此問題,我們將使用該數字的二進位制位。並生成該數字的第 k 位。為此,我們將使用該數字的二進位制移位並將該數字左移 (k-1) 次。現在執行移位數字和原始數字的結束操作,這將提供第 k 位的值。
示例
以下程式碼將展示我們解決方案的實現
#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;
}輸出
3th significant bit of 12 is : 1
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP