# LeetCode : 0191. Number of 1 Bits (bits)
###### tags:`leetcode`
```
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <unordered_map>
using std::vector;
using std::unordered_map;
using namespace std;
class BaseVectorPrint {
public:
void BasePrint00(vector<int>& num) {
for (size_t i = 0; i < num.size(); ++i) {
cout << "[" <<num.at(i) << "]" << "; ";
}
cout << endl;
}
void BasePrint01(vector<int>& num) {
for (size_t i = 0; i < num.size(); ++i) {
cout << num[i] << "; ";
}
cout << endl;
}
void BasePrint02(vector<int>& num) {
for (const auto &item : num) {
cout << item << "; ";
}
cout << endl;
}
void TwoDimensionalPrint(vector<vector<int>> &num){
for (int i = 0; i < num.size(); i++)
{
for (int j = 0; j < num[i].size(); j++)
{
cout << "[" << num[i][j] << "]";
}
cout << endl;
}
}
};
class Solution01 {
public:
int hammingWeight(uint32_t n) {
int count=0;
while (n) {
// let's and(&) each bit with 1, if the result is 1 then we increment count by 1
if (n&1 > 0) count++;
// and then shift n by 1 bit [so that we can check the next bit is 1 or not]
n>>=1;
}
return count;
}
};
class Solution02 {
public:
int hammingWeight(uint32_t n) {
int count=0;
while (n) {
// when we substract n by 1, the Lowest significant 1 is affected first, thus
// when we use and (&) operation the other 1's stay intact and we increment count by 1
n &= (n-1);
count++;
}
return count;
}
//sample run
// iunput number 5 = 1001
// one step = n-1 = 4 = 1000
// 1001 & 1000 = 1000
// two step = n-1 = 3 = 0111
// 1000 & 0111 = 0
// out function and return count.
};
int main(void)
{
BaseVectorPrint printVector;
Solution02 runfunc;
vector<int> test01 = { 4, 5, 1, 8, 2 };
vector<int> test02 = { 1, 2, 3, 4 };
vector<int> test03 = { -1, 1, 0, -3, 3 };
vector<int> ans ;
int input_number = 31;
int input_number2 = 5;
int intans;
intans = runfunc.hammingWeight(input_number2);
//printVector.BasePrint00(ans);
printf("all 1 counts = %d\n",intans);
printf("test\n");
system("pause");
}
```
> Tip opeator shift 【>>】