C++ __builtin_popcount() Function
Last Updated :
05 Sep, 2023
__builtin_popcount() is a built-in function of GCC compiler. This function is used to count the number of set bits in an unsigned integer. In other words, it counts the number of 1’s in the binary form of a positive integer.
Syntax:
__builtin_popcount(int number);
Parameter: This function only takes unsigned or positive integers as a parameter.
Return Value: Number of set bits in the given number.
Illustration:
Input: n = 5
binary value of 5: 101
Output: 2
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n = 4;
cout << __builtin_popcount(n);
return 0;
}
|
Time Complexity(b), where b is the number of bits.
Auxiliary Space: O(1)
What will happen if the data type is of type long long?
__builtin_popcount() is a GCC extension that is used to count the number of set bits in long long data types.
Syntax:
__builtin_popcountll(long long number);
Example:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long n = 1e15;
cout << __builtin_popcountll(n);
return 0;
}
|
Share your thoughts in the comments
Please Login to comment...