__builtin_popcount (GNU内建函数)
内部使用查表法实现
https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html
int __builtin_popcount(unsigned int)
int __builtin_popcountl(unsigned long int)
int __builtin_popcountll(unsigned long long int)
#include <cstdio>
int main(){
int n, x;
scanf("%d", &n);
while(n--){
scanf("%d", &x);
printf("%d ", __builtin_popcount(x));
}
return 0;
}
std::popcount (C++20)
https://en.cppreference.com/w/cpp/numeric/popcount
template<class T>
constexpr int popcount(T x) noexcept;
#include <bit>
#include <cstdio>
int main(){
int n, x;
scanf("%d", &n);
while(n--){
scanf("%d", &x);
printf("%d ", std::popcount((unsigned)x));
}
return 0;
}