1. 程式人生 > >__builtin_popcount() 函數

__builtin_popcount() 函數

print div class 個數字 使用 因此 true std ()

詳解

該函數的主要作用是計算一個數字的二進制中有多少個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",n-ans);
    return 0;
}

  

__builtin_popcount() 函數