Secret Origins

来源:互联网 发布:同花顺炒股交易软件 编辑:程序博客网 时间:2024/05/21 07:09

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

Sample Output

Case 1: 27

Case 2: 14241

Case 3: 395

Case 4: 11

Case 5: 16

分析:求解n之后第一个和它二进制相同的数,暴力法,真是超时。。。。。

膜大佬的位运算方案:

可以通过一下步骤:

(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)要求的值。

import java.util.*; public  class Main{    static Scanner in = new Scanner(System.in);    public static void main(String args[]){         int k=in.nextInt();          int ca = 0;        while(k-->0){           ca++;            int n = in.nextInt();              int x = n & -n, y = n + x;              n = ((n & ~y) / x >> 1) | y;            System.out.println("Case "+ca+": "+ n);        }         }    }

瑟瑟发抖。。。。根本想不到。。。
原创粉丝点击