This is the tale of Zephyr, the greatest time traveler the world will never know. Even those who are aware of Zephyr's existence know very little about her. For example, no one has any clue as to which time period she is originally from.
But we do know the story of the first time she set out to chart her own path in the time stream. Zephyr had just finished building her time machine which she named - "Dokhina Batash". She was making the final adjustments for her first trip when she noticed that a vital program was not working correctly. The program was supposed to take a numberN, and find what Zephyr called its Onoroy value.
The Onoroy value of an integer N is the number of ones in its binary representation. For example, the number 13 (11012) has an Onoroy value of 3. Needless to say, this was an easy problem for the great mind of Zephyr. She solved it quickly, and was on her way.
You are now given a similar task. Find the first number after N which has the same Onoroy value asN.
Input
Input starts with an integer T (≤ 65), denoting the number of test cases.
Each case begins with an integer N (1 ≤ N ≤ 109).
Output
For each case of input you have to print the case number and the desired result.
Sample Input
5
23
14232
391
7
8
Sample Output
Case 1: 27
Case 2: 14241
Case 3: 395
Case 4: 11
Case 5: 16
解题目的思路就是
先找出一个01的 然后将其对调还有记录后面有多少0 和1 将0放在对调之后 剩下的1 全放在后面
之后算一遍就好了
稍微有个地方需要注意的就是 如果第一位是1的话那么找不到0 所以刚开始就得吧所有的第一位当成0这样子就可以了这是贪心的思想
位运算的话 等我明天学学
代码:
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
using namespace std;
int digit[100];
int dd[100];
int main()
{
int t,n,m,i,j;
scanf("%d",&t);
for(int o=1;o<=t;o++)
{
scanf("%d",&n);
m=n;
i=0;
while(m!=0)
{
digit[++i]=m%2;
m=m/2;
}
dd[0]=0;
for(int k=1;k<=i;k++)
dd[k]=digit[i-k+1];
//已经求出了遍历后的东西了 然后现在要做的就是 从后面查找那个为01那么对对调一下
int len=i;
int cnt0=0,cnt1=0;
int pos;
for(i=len;i>=0;i--)
{
if(dd[i]==1&&dd[i-1]==0)
{
dd[i]=0;
dd[i-1]=1;
pos=i+1;
break;
}
else
{
if(dd[i]==1)cnt1++;
else if(dd[i]==0)cnt0++;
}
}
for(j=0;j<cnt0;j++)
dd[pos++]=0;
for(j=0;j<cnt1;j++)
dd[pos++]=1;
int x=dd[len]*1;
int a=1;
for(j=len-1;j>=0;j--)
{
a=a*2;
x=x+a*dd[j];
}
printf("Case %d: %d\n",o,x);
}
return 0;
}