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;
}
运行效果如下:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探