C/C++ 程式如何計算整數中的設定位數?
這裡,我們將瞭解如何檢查整數中的設定位數。設定位是數字二進位制表示法中的 1。例如,數字 13 有三個設定位 1101。因此,計數將是 3。
要解決此問題,我們將數字向右移位,如果 LSB 為 1,則增加計數。程式將一直執行,直到數字變為 0。
演算法
countSetBit()
begin count := 0 while count is not 0, do if LSb of n is set, then count := count + 1 end if n := n after shifting 1 bit to right done return count end
示例
#include<iostream>
using namespace std;
int count_set_bit(int n) {
int count = 0;
while(n != 0) {
if(n & 1 == 1) {
count++;
}
n = n >> 1; //right shift 1 bit
}
return count;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Number of set bits: " << count_set_bit(n);
}輸出
Enter a number: 29 Number of set bits: 4
該程式可以在 C 中執行並生成輸出,但是當我們想要在 C++ 中編譯它時,它將在編譯期間返回錯誤。它會提示有太多引數被傳遞過來了。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP