int count_one (int n)
{
while( n )
{
n = n&(n-1);
count++;
}
return count;
}
//WAP to find setbits (total 1's in binary ex. n= 5 => 101 => 2 setbits
int count{}, num{};
cin >> num;
while (num > 0) {
count = count + (num & 1); // num&1 => it gives either 0 or 1
num = num >> 1; // bitwise rightshift
}
cout << count; //count is our total setbits
Code Example |
---|
Cpp :: c++ first letter of string |
Cpp :: char ascii c++ |
Cpp :: iterate over 2 vectors c++ |
Cpp :: c++ for else |
Cpp :: matrix transpose in c++ |
Cpp :: increment c++ |
Cpp :: get value of enum cpp |
Cpp :: casting c++ |
Cpp :: comparator for priority queue c++ |
Cpp :: c++ get type name of object |
Cpp :: string.begin() c++ |
Cpp :: how to make an overloaded constructor in c++ |
Cpp :: console colors in C++ |
Cpp :: c++ cout format |
Cpp :: for loop c++ |
Cpp :: c++ string size |
Cpp :: c++ function default argument |
Cpp :: stoi function in c++ library |
Cpp :: abs in cpp |
Cpp :: Header for INT_MIN |
Cpp :: cpp mutex |
Cpp :: float to int c++ |
Cpp :: Find the biggest element in the array |
Cpp :: c++ erase remove |
Cpp :: length of array c++ |
Cpp :: vector library c++ |
Cpp :: size() in c++ SET |
Cpp :: c++ get last element in vector |
Cpp :: find function in c++ |
Cpp :: c++ recursion |