LightOJ1042 - Secret Origins (位运算)

来源:互联网 发布:淘宝店宝贝图片怎么弄 编辑:程序博客网 时间:2024/05/17 08:47
1042 - Secret Origins
PDF (English)StatisticsForum
Time Limit: 0.5 second(s)Memory Limit: 32 MB

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

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最大可以去到1e9,所以可以知道,暴力一个个枚举是行不通的。题目要求输出二进制表示中1的位数相同的首个大于N的数,所以应该不难想到要用位运算去寻找答案。

在《挑战程序设计竞赛》这本书中,在谈到集合的那一部分,有一个关于用位运算表示集合的专栏,里面的介绍就有本题解法的相关知识。

我们可以知道,0101110之后的是0110011,0111110之后的是1001111。那么怎么通过位运算快速得得到我们想要的数呢。

可以通过一下步骤:

(1)求出最低位的1开始的连续的1的区间(0101110->0001110) 

(2)将这一区间全部变为0,并将区间左侧的那个0变为1(0101110->0110000)

(3)将第(1)步里取出的区间右移,直到剩下的1的个数减少了1个(0001110->0000011)

(4)将第(2)步和第(3)步的结果按位取或(0110000|0000011=0110011)

对于为零的整数,N&(-N)的值就是将其最低位的1独立出来后的值。这是由于计算机中负数采用二进制补码表示,-N实际上对应于(~N)+1(将N按位取反然后加上1)。

将最低位的1取出后,设它为x。那么通过计算y=N+x,就将N从最低位的1开始的连续的1都置为0了。我们来比较一下~y和N。在N中加入x后没有变化的位,在~y中全部取相反的值。而最低位1开始的连续区间在~y中依然是1,区间左侧的那个0在~y中也依然是0。于是通过计算z=N&~y就得到了最低位1开始的连续区间。比如如果N=0101110,则x=0000010,y=0110000,z=0001110。

同时,y也恰好是第(2)步要求的值那么首先将z不断右移,知道最低位为1,这通过计算z/x即可完成。这样再将z/x右移1位就得到了第(3)要求的值。

#include <cstdio>using namespace std;int main(){    int cases, caseno = 0;    scanf("%d", &cases);    while(cases--) {        int n;        scanf("%d", &n);        int x = n & -n, y = n + x;        n = ((n & ~y) / x >> 1) | y;        printf("Case %d: %d\n", ++caseno, n);    }    return 0;}


0 0
原创粉丝点击