ที่นี่เราจะดูว่าเราสามารถตรวจสอบจำนวนบิตชุดในจำนวนเต็มได้อย่างไร ชุดบิตคือ 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++ มันจะส่งคืนข้อผิดพลาดระหว่างเวลาคอมไพล์ จะบอกว่ามีการโต้แย้งมากเกินไป