方案1:开辟超大数据,记录arr[2i]=i
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
const int MAX_N = 1 << 20;
int H[MAX_N + 1];
for (int i = 0; i <= 20; i++) H[1 << i] = i;
while (cin >> n) { // 对多次询问求解
while (n > 0) {
cout << H[n & -n] << " "; // 第几位为1
n -= (n & -n); // 减去最近的1往后的数
}
cout << endl;
}
return 0;
}
方案2:利用数学技巧,大幅降低数组空间到arr[37]
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
int H[37]; // 2^k对37取余,互不相等,且正好取遍整数1-36
for (int i = 0; i < 36; i++) H[(1ll << i) % 37] = i;
while (cin >> n) { // 对多次询问求解
while (n > 0) {
cout << H[(n & -n) % 37] << " "; // 第几位为1
n -= (n & -n); // 减去最近的1往后的数
}
cout << endl;
}
return 0;
}