📜  C ++ STL中的bitset count()

📅  最后修改于: 2021-05-31 19:03:02             🧑  作者: Mango

bitset :: count()是C++中的内置STL,它以数字的二进制表示形式返回设置的位数。

句法:

int count() 

参数:该函数接受任何参数。

返回值:该函数返回设置的位数。如果传递的数字是整数,则以数字的二进制表示形式返回1的总数或设置位数。

下面的程序说明了bitset :: count()函数。

程序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;
}
输出:
1100 has 2 set bit
001000 has 1 set bit

程式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;
}
输出:
0000 has 0 set bit
0010 has 1 set bit
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”