用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++中进行编译时,它将在编译期间返回错误。它会说传递了太多的参数。