lowbit运算加Hash找出整数二进制表示下所有是1的位

预备知识https://www.cnblogs.com/fx1998/p/12826831.html

当输入的数n较小时,直接开一个数组H

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 const int N = 1 << 20;
 4 //2 ^ 20 = 1048576
 5 int H[N + 10];
 6 int main() {
 7     for (int i = 0; i <= 20; i++) { //预处理
 8         H[1 << i] = i;
 9     }
10     int n;
11     while (cin >> n) {
12         while (n > 0) {
13             cout << H[n & -n] << " ";
14             n -= n & -n;
15         }
16         cout << endl;
17     }
18     return 0;
19 }

运行结果及解释:

 然后根据二进制码8421

9的二进制表示为  1001

7的二进制表示为  0111

4的二进制表示为  0100

然后从右往左从0开始数的话:

9的第0位,第3位是1,所以输出0 3

7的第0位,第1位是1,第2位是1,所以输出0 1 2

4的第2位是1,所以输出2

然后是稍微复杂但效率更高的方法

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 //2 ^ 35 = 34,359,738,368。要开long long
 4 int H[37];
 5 int main() {
 6     for (int i = 0; i < 36; i++) { //预处理
 7         H[(1ll << i) % 37] = i;
 8     }
 9     int n;
10     while (cin >> n) {
11         while (n > 0) {
12             cout << H[(n & -n) % 37] << " ";
13             n -= n & -n;
14         }
15         cout << endl;
16     }
17     return 0;
18 }

lowbit运算是树状数组的一个基本操作,在之后会学到

posted @ 2020-10-28 15:21  kyk333  阅读(121)  评论(0)    收藏  举报