-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbitcount.cpp
More file actions
46 lines (44 loc) · 929 Bytes
/
bitcount.cpp
File metadata and controls
46 lines (44 loc) · 929 Bytes
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
42
43
44
45
46
#include <iostream>
#include <cstdio>
constexpr int onecount(unsigned int i) {
int c = 0;
while(i != 0) {
if(i & 1) {
c++;
}
i = i >> 1;
}
return c;
}
constexpr int zerocount(unsigned int i) {
int c = 0;
while(i != 0) {
if (~i & 1) {
c++;
}
i = i >> 1;
}
return c;
}
constexpr int whole_amount(unsigned int i) {
int c = 0;
while(i != 0) {
if(i | 0) {
c++;
}
i = i >> 1;
}
return c;
}
int main() {
int num {};
std::cout << "Enter number: ";
std::cin >> num;
if (!std::cin) {
std::cerr << "Not a number \n";
std::cerr.flush();
return -1;
}
printf("%b", num);
std::cout << " returns " << onecount(num) << " units, " << zerocount(num) << " zeros, and whole amount of bits " << whole_amount(num) << std::endl;
}