最近刷题遇见一个很有意思的函数:__builtin_popcount()
查看文档发现其作用是计算x表示成二进制时有多少个1(32位).
例如:https://leetcode-cn.com/problems/prime-number-of-set-bits-in-binary-representation/
class Solution {
public:
int countPrimeSetBits(int left, int right) {
int ans = 0;
for (int x = left; x <= right; ++x) {
if ((1 << __builtin_popcount(x)) & 665772) {
++ans;
}
}
return ans;
}
};