算法 - 位运算


常见的两种操作,一个是找第几位的值是几,一个是找最后一个1是多少lowbit。

找第几位的值是几: 向右边移动k为然后进行与运算。 x >> k & 1

lowbit操作: x & -x, -x等于反码+1

来源:

https://www.acwing.com/problem/content/description/803/

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
#include <iostream>

using namespace std;
const int N = 1e5 + 5;
int a[N];
int n;

int lowbit(int x)
{
return x & -x;
}

int main()
{
cin >> n;
for(int i = 0; i < n; i++) cin >> a[i];

for(int i = 0; i < n; i++)
{
int res = 0;
while (a[i]) a[i] -= lowbit(a[i]), res++;
printf("%d ", res);
}
return 0;
}

或者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

#include <iostream>

using namespace std;

int main()
{
int n;
scanf("%d", &n);
while (n -- )
{
int x, s = 0;
scanf("%d", &x);

for (int i = x; i; i -= i & -i) s ++ ;

printf("%d ", s);
}

return 0;
}