求出二进制的低位(从最先出现1的位置截断),其实就是位运算x^(-x)
#include <iostream>
#include <algorithm>
using namespace std;
int lowbit(int x)
{
return x&(-x);
}
int main()
{
int a[100001],ans,b[100001];
a[0]=0;
for (int i=1; i<100001; i++)
{
a[i]=lowbit(i);
}
int sum,L;
while (cin>>sum>>L)
{
ans=0;
for (int i=L; i&& sum; i--)
{
if(sum>=a[i])
{
b[ans++]=i;
sum-=a[i];
}
}
if(sum==0)
{
cout<<ans<<endl;
for (int i=0; i<ans; i++)
{
if(i==ans-1)
{
cout<<b[i]<<endl;
}
else
{
cout<<b[i]<<" ";
}
}
}
else
{
cout<<"-1"<<endl;
}
}
return 0;
}