首页 > 代码库 > [POJ] 2453 An Easy Problem [位运算]

[POJ] 2453 An Easy Problem [位运算]

An Easy Problem
 

Description

As we known, data stored in the computers is in binary form. The problem we discuss now is about the positive integers and its binary form. 

Given a positive integer I, you task is to find out an integer J, which is the minimum integer greater than I, and the number of ‘1‘s in whose binary form is the same as that in the binary form of I. 

For example, if "78" is given, we can write out its binary form, "1001110". This binary form has 4 ‘1‘s. The minimum integer, which is greater than "1001110" and also contains 4 ‘1‘s, is "1010011", i.e. "83", so you should output "83".

Input

One integer per line, which is I (1 <= I <= 1000000). 

A line containing a number "0" terminates input, and this line need not be processed.

Output

One integer per line, which is J.

Sample Input

1234780

Sample Output

245883

Source

POJ Monthly,zby03
 
题解:输入一个整数x,求一个数y,使得y的二进制各位上1的个数和等于x的二进制各位上1的个数和,y>x,y尽量小。直接每次加1,统计各位上1的个数,每次求y末尾是否为1,直接判断y是否为奇数即可,然后y>>=1,右移一位。
代码:
 1 #include<cstdio> 2 #include<algorithm> 3  4 using namespace std; 5  6 int main() 7 { 8     int p,x,num1,num2; 9 10     while(1) {11         num1=0;num2=0;12         scanf("%d",&x);13         if(!x) break;14         p=x;15         while(p>0) {16             if(p%2!=0) num1++;17             p>>=1;18         }19         while(1) {20             x++;21             p=x;22             num2=0;23             while(p>0) {24                 if(p%2!=0) num2++;25                 p>>=1;26             }27             if(num2==num1) {28                 printf("%d\n",x);29                 break;30             }31             32         }33     }34     35     return 0;36 }

 

[POJ] 2453 An Easy Problem [位运算]