__builtin_popcount() 函数

详解

该函数的主要作用是计算一个数字的二进制中有多少个1,返回值就是其中1的个数。

它使用一张基于表的方法来进行位搜索,因此这个操作的执行效率很高

此处举一题

P1582 倒水

#include <bits/stdc++.h>
using namespace std;
#define lowbit(x) x&(-x)
int main()
{
    int n,k;
    scanf("%d%d",&n,&k);
    int ans=n;
    while(__builtin_popcount(n)>k)
    {
        n+=lowbit(n);
    }
    printf("%d
",n-ans);
    return 0;
}

计算一个 32 位无符号整数有多少个位为 1

The desire of his soul is the prophecy of his fate
你灵魂的欲望,是你命运的先知。

原文地址:https://www.cnblogs.com/RioTian/p/13527421.html