-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitcount.cpp
42 lines (39 loc) · 1 KB
/
bitcount.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char *argv[]) {
for (size_t i = 1; i < (size_t) argc; ++i) {
string str(argv[i]);
unsigned int number;
size_t pos = 0;
size_t arg_len = str.size();
try {
number = stoul(str, &pos);
}
catch (...) {
cout << -1 << endl;
continue;
}
if (pos != arg_len) {
cout << -1 << endl;
continue;
}
// first method
unsigned int bitscount = 0;
for (size_t k = 0; k < 32; ++k) {
unsigned int shifted = number >> k;
if (shifted == 0) {
break;
}
if (shifted & 1) {
++bitscount;
}
}
// second method
unsigned int bitscount2 = __builtin_popcount(number);
if (bitscount == bitscount2)
cout << bitscount << endl;
else
cout << "-1";
}
}