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