1042 - Secret Origins (位运算好题)

      1042 - Secret Origins
Time Limit: 0.5 second(s)Memory Limit: 32 MB


This is the tale of Zephyr, the greatest time traveler theworld will never know. Even those who are aware of Zephyr's existence know verylittle about her. For example, no one has any clue as to which time period sheis originally from.

But we do know the story of the first time she set out tochart her own path in the time stream. Zephyr had just finished building hertime machine which she named - "Dokhina Batash". She was making thefinal adjustments for her first trip when she noticed that a vital program wasnot working correctly. The program was supposed to take a numberN, andfind what Zephyr called its Onoroy value.

The Onoroy value of an integer N is the number of onesin its binary representation. For example, the number 13 (11012) hasan Onoroy value of 3. Needless to say, this was an easy problem for the greatmind of Zephyr. She solved it quickly, and was on her way.

You are now given a similar task. Find the first numberafter 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 andthe desired result

Sample Input

Output for Sample Input

5

23

14232

391

7

8

Case 1: 27

Case 2: 14241

Case 3: 395

Case 4: 11

Case 5: 16



题目大意: 给你一个n,求出大于n但是二进制的1的个数跟n相同的数。

例如: 010110->011001

首先数据很大,模拟的话肯定超时;

看到二进制就要有位运算的联想,,,如果没有联想到位运算的话,,,就很难有思路了

然后通过贪心找规律,,,最后通过代码实现也需要思维和技巧,是一道质量很高的位运算题,,,

通过观察我们发现只要出现第一01时把01改成10  并把次01后面的1都压到最后面就可以了

例如01(01)(111100)->01(10)(001111), 通过这样就可以得出答案。



.#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;


int main()
{
    int t, ncase=1;
    scanf("%d", &t);
    while(t--)
    {
        int n;
        scanf("%d", &n);
        int cnt=0;
        for(int i=1;i<=30;i++)
        {
            if(n&1)
            {
                cnt++;
                if(((n>>1)&1)==0)
                {
                    n=(n>>1)+1;
                    n=n<<i;
                    for(int j=0;j<cnt-1;j++)
                    {
                        n=n|(1<<j);
                    }
                    break;
                }
            }
            n>>=1;
        }
        printf("Case %d: %d\n",ncase++,n);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值