LightOJ 1042 - Secret Origins

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 number N, 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 as N.

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

Output for Sample Input

Case 1: 27
Case 2: 14241
Case 3: 395
Case 4: 11
Case 5: 16

题目大意

在所给数字N后面找出第一个数字满足它的二进制数中1的数量等于N的二进制数中1的数量。

那么只需要将N转化成二进制数,将这个二进制数看成一个排列,只需求出下一个排列,就可以了。

注意: 防止N是最大的全排列,这样就没有了下一个排列,所以将这个二进制数字前面补一个0,这样它的下一个排列恒存在。

#include<bits/stdc++.h>
using namespace std;


unsigned int solve()
{
    unsigned int n;
    cin >> n;
    string str;
    while(n)
    {
        if(n & 1)
            str += '1';
        else
            str += '0';
        n >>= 1;
    }
    str += '0';
    reverse(str.begin(), str.end());
    next_permutation(str.begin(), str.end());
    unsigned int ans = 0;
    for(int i=0; i<str.size(); ++ i)
        ans = ans * 2 + str[i] - '0';
    return ans;
}
int main()
{
    ios::sync_with_stdio(false);
	
    int t;
    cin >> t;
    for(int i=0; i<t; ++ i)
    {
        cout << "Case " << i+1 << ": " << solve() << endl;
    }
    return 0;
}

posted @ 2017-04-12 21:03  aiterator  阅读(233)  评论(0编辑  收藏  举报