C++ __builtin_popcount函数作用

32a531d6-4b88-4814-a3f7-e35024af9a2d

__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;
}

运行效果如下:

posted @   不怕困难的博客  阅读(224)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
点击右上角即可分享
微信分享提示