AcWing_801 二进制中1的个数(位运算/系统函数/bitset)

AcWing

801. 二进制中1的个数

系统自带函数,并不在某个头文件中,即只要写了main函数,就可以使用。OI中可用。

cout << __builtin_popcount(x) << ' ';

返回x在二进制下1的个数,时间复杂度$O(loglogx)$或$O(1)$.

#include <iostream>
using namespace std;
int main(){
    int x; cin >> x;
    while(cin >> x) cout << __builtin_popcount(x) << ' ';
    return 0;
}

bitset

#include <bitset>

bitset<32> ar; //默认全为0
bitset<32> ar(n); //n的二进制
bitset<32> ar(str); //01串
bitset<n> ar(str, pos, n); //从str第p位开始的n位
#include <bitset>

ar.size();//返回位数
ar.count();//返回1的个数
ar.any();//返回是否有1
ar.none();//返回是否没有1
ar.test(p);//返回第p位是不是1
ar.set();//全部设为1
ar.set(p);//第p位设为1
ar.reset();//全部设为0
ar.reset(p);//第p位设为0
ar.flip();//全部反转
ar.flip(p);//第p位反转
ar.to_ulong();//返回unsigned long
ar.to_ullong();//返回unsigned long long
ar.to_string();//返回string

代码:

#include <iostream>
#include <bitset>
using namespace std;

int main(){
    int n;
    cin >> n;
    while (n --){
        int x;
        cin >> x;
        bitset<32> b = x;
        cout << b.count() << ' ';
    }
    return 0;
}

位运算的做法,可以定义lowbit()函数:

int lowbit(int x){
    return x & -x;
}

代码:

#include <iostream>
using namespace std;

int lowbit(int x){
    return x & -x;
}

int main(){
    int n;
    scanf("%d", &n);
    while (n --){
        int x, s = 0;
        scanf("%d", &x);
        for (int i = x; i; i -= lowbit(i)) s ++;
        printf("%d ", s);
    }
    return 0;
}