-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
76 lines (62 loc) · 812 Bytes
/
main.cpp
File metadata and controls
76 lines (62 loc) · 812 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// 计算二进制中1的个数
#include <iostream>
#include <vector>
#include <algorithm>
// 常规解法
int Fun1(int num)
{
std::vector<int> vec;
while (num)
{
vec.push_back(num % 2);
num /= 2;
}
return std::count(vec.begin(), vec.end(), 1);
}
// 位运算, 但是负数会导致死循环
// 负数右移时会以1填充
int Fun2(int num)
{
int count = 0;
while (num)
{
if (num & 1)
++count;
num = num >> 1;
}
return count;
}
// 位运算常规解法
int Fun3(int num)
{
int count = 0;
unsigned flag = 1;
while (flag)
{
if (num % flag)
++count;
flag = flag << 1;
}
return count;
}
// 最佳解法
int Fun4(int num)
{
int count = 0;
while (num)
{
++count;
num = (num - 1) & num;
}
return count;
}
int main()
{
int num;
std::cin >> num;
Fun1(num);
Fun2(num);
Fun3(num);
Fun4(num);
return 0;
}