Skip to content
Related Articles
bitset count() in C++ STL
• Difficulty Level : Basic
• Last Updated : 18 Jun, 2018

bitset::count() is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number.

Syntax:

```int count()
```

Parameter: The function accepts no parameter.

Return Value: The function returns the number of set bits. It returns the total number of ones or the number of set bits in the binary representation of the number if the passed number is an integer.

Below programs illustrates the bitset::count() function.

Program 1:

 `// CPP program to illustrate the``// bitset::count() function``#include ``using` `namespace` `std;`` ` `int` `main()``{``    ``// Initialisation of a bitset``    ``bitset<4> b1(string(``"1100"``));``    ``bitset<6> b2(string(``"001000"``));`` ` `    ``// Function to count the``    ``// number of set bits in b1``    ``int` `result1 = b1.count();``    ``cout << b1 << ``" has "` `<< result1``         ``<< ``" set bit\n"``;`` ` `    ``// Function to count the``    ``// number of set bits in b2``    ``int` `result2 = b2.count();``    ``cout << b2 << ``" has "` `<< result2``         ``<< ``" set bit"``;`` ` `    ``return` `0;``}`
Output:
```1100 has 2 set bit
001000 has 1 set bit
```

Program 2:

 `// CPP program to illustrate the``// bitset::count() function``// when the input is an integer``#include ``using` `namespace` `std;`` ` `int` `main()``{``    ``// Initialisation of a bitset``    ``bitset<4> b1(16);``    ``bitset<4> b2(18);`` ` `    ``// Function to count the``    ``// number of set bits in b1``    ``int` `result1 = b1.count();``    ``cout << b1 << ``" has "` `<< result1``         ``<< ``" set bit\n"``;`` ` `    ``// Function to count the``    ``// number of set bits in b2``    ``int` `result2 = b2.count();``    ``cout << b2 << ``" has "` `<< result2``         ``<< ``" set bit"``;`` ` `    ``return` `0;``}`
Output:
```0000 has 0 set bit
0010 has 1 set bit
```
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for the language and STL. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up