介绍
__builtin_popcount()
是一个在 GCC中提供的内置函数,用于计算一个整数中二进制表示的1的个数。
函数原型
函数格式有以下分类:
#include <stdio.h> //使用的头文件
int __builtin_popcount(unsigned int x); //对于无符号32位整数:
int __builtin_popcountl(unsigned long x); //对于无符号64位整数:
int __builtin_popcountll(unsigned long long x); //对于无符号128位整数:
这个函数通常用于位操作、算法优化以及其他需要快速统计二进制中1的数量的应用场景。
函数运用实例(leetcode实例)
第一题
191. 位1的个数https://leetcode.cn/problems/number-of-1-bits/题目
编写一个函数,获取一个正整数的二进制形式并返回其二进制表达式中
设置位
的个数(也被称为汉明重量)。
函数引用:
class Solution {
public:
int hammingWeight(int n) {
return __builtin_popcount(n);
}
};
代码分析
利用__builtin_popcount()函数,将hammingWeight()函数传入的参数直接传入,获取当前输入十进制参数转为二进制后1的个数,再将该结果直接返回。
第二题
338. 比特位计数https://leetcode.cn/problems/counting-bits/
题目
给你一个整数
n
,对于0 <= i <= n
中的每个i
,计算其二进制表示中1
的个数 ,返回一个长度为n + 1
的数组ans
作为答案。
函数引用:
class Solution {
public:
vector<int> countBits(int n) {
vector<int> nums;
for(int i=0;i<=n;i++){
nums.push_back(__builtin_popcount(i));
}
return nums;
}
};
代码分析
1.使用vector容器创建数组nums;
2.使用for循环,从0到n,将每个值传入__builtin_popcount()函数获取对应的二进制1的个数;
3.将得到的结果加入nums数组中,最后作为结果返回。