[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

1
2
3
4
78
0

Sample Output

2
4
5
8
83

Source

 
题解:输入一个整数x,求一个数y,使得y的二进制各位上1的个数和等于x的二进制各位上1的个数和,y>x,y尽量小。直接每次加1,统计各位上1的个数,每次求y末尾是否为1,直接判断y是否为奇数即可,然后y>>=1,右移一位。
代码:
 #include<cstdio>
#include<algorithm> using namespace std; int main()
{
int p,x,num1,num2; while() {
num1=;num2=;
scanf("%d",&x);
if(!x) break;
p=x;
while(p>) {
if(p%!=) num1++;
p>>=;
}
while() {
x++;
p=x;
num2=;
while(p>) {
if(p%!=) num2++;
p>>=;
}
if(num2==num1) {
printf("%d\n",x);
break;
} }
} return ;
}
上一篇:Redis介绍、安装、配置


下一篇:使用Tomcat的Reload提高开发速度(翻译)