题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=412
思路:从n的二进制中从右往左寻找第一个01,然后将01右边的1全都移到最右边;
用的是bitset
声明: bitset<32> bt(n) 代表n的二进制存在了bt中,bt[i]上的数字代表n的二进制中的各个数字,bt.to_ulong()是将bt以无符号长整型输出出来。
代码:
#include <iostream>
#include <bitset>
using namespace std;
int main()
{
int n;
while(cin >> n)
{
int i,cnt,j;
bitset<32> bt(n);
for(i = cnt = 0;i < 32;++i)
{
if(bt[i]) cnt++;
if(bt[i] && !bt[i + 1])
{
bt[i] = false;
bt[i + 1] = true;
j = i;
break;
}
}
--cnt;
for(i = 0;i < cnt;++i)
bt[i] = true;
for(;i < j;++i)
bt[i] = false;
cout << bt.to_ulong() << endl;
}
return 0;
}