當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ __builtin_popcount()用法及代碼示例

__builtin_popcount() 是 built-in function of GCC compiler 。該函數用於計算無符號整數中設置的位數。換句話說,它計算正整數的二進製形式中 1 的數量。

用法:

__builtin_popcount(int number);

參數:該函數僅接受無符號或正整數作為參數。

返回值:給定數量中設置的位數。

示例:

Input: n = 5
binary value of 5: 101
Output: 2

例子:

C++


// C++ code to demonstrate the
// __builtin_popcount function
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int n = 4;
    // Printing the number of set bits in n
    cout << __builtin_popcount(n);
    return 0;
}
輸出
1

時間複雜度(b),其中b是位數。
輔助空間:O(1)

如果數據類型是long long類型會發生什麽?

__builtin_popcount() 是一個 GCC 擴展,用於計算 long long 數據類型中設置的位數。

用法:

__builtin_popcountll(long long number);

例子:

C++


// C++ code to demonstrate the
// __builtin_popcount function
#include <bits/stdc++.h>
using namespace std;
int main()
{
    long long n = 1e15;
    // Printing the number of set bits in n
    cout << __builtin_popcountll(n);
    return 0;
}
輸出
20


相關用法


注:本文由純淨天空篩選整理自amankr0211大神的英文原創作品 C++ __builtin_popcount() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。