__builtin_popcount函数是系统自带的一个返回值是int/long/long long二进制'1'的个数的函数。
对于int,long, long long分别用一下三种函数:
__builtin_popcount(unsigned int n)//返回值为int
__builtin_popcountl(unsigned int n)//返回值为long
__builtin_popcountll(unsigned int n)//返回值为long long
拿__builtin_popcount(unsigned int n)举个例子
#include <bits/stdc++.h>
using namespace std;
unsigned int n;
int ak[100];
int len;
//由十进制转为二进制
void tentotwo(unsigned int a) {
len = 0;
while(a / 2) {
ak[++len] = a % 2;
a /= 2;
}
}
int main() {
printf("请输入一个十进制:");
cin >> n;
printf("二进制:");
for(int i = len; i >= 1; i--) cout << ak[i];
cout << endl;
printf("二进制1个数:");
cout << __builtin_popcount(n) << endl;
return 0;
}
运行效果如下: