__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
相關用法
- C++ _Exit()用法及代碼示例
- C++ cos()用法及代碼示例
- C++ sin()用法及代碼示例
- C++ asin()用法及代碼示例
- C++ atan()用法及代碼示例
- C++ atan2()用法及代碼示例
- C++ acos()用法及代碼示例
- C++ tan()用法及代碼示例
- C++ sinh()用法及代碼示例
- C++ ceil()用法及代碼示例
- C++ tanh()用法及代碼示例
- C++ fmod()用法及代碼示例
- C++ acosh()用法及代碼示例
- C++ asinh()用法及代碼示例
- C++ floor()用法及代碼示例
- C++ atanh()用法及代碼示例
- C++ log()用法及代碼示例
- C++ trunc()用法及代碼示例
- C++ round()用法及代碼示例
- C++ lround()用法及代碼示例
- C++ llround()用法及代碼示例
- C++ rint()用法及代碼示例
- C++ lrint()用法及代碼示例
- C++ log10()用法及代碼示例
- C++ modf()用法及代碼示例
注:本文由純淨天空篩選整理自amankr0211大神的英文原創作品 C++ __builtin_popcount() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。