NOI 4.6 贪心 1455: An Easy Problem

题目来源:http://noi.openjudge.cn/ch0406/1455/

1455: An Easy Problem

总时间限制1000ms       内存限制65536kB

描述

As we known, data stored in the computers is in binary form. Theproblem 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 theminimum integer greater than I, and the number of '1's in whose binary form isthe 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 isgreater than "1001110" and also contains 4 '1's, is"1010011", i.e. "83", so you should output "83".

输入

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

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

输出

One integer per line, which is J.

样例输入

1
2
3
4
78
0

样例输出

2
4
5
8
83

来源

POJ Monthly,zby03

 -----------------------------------------------------

思路

如果有孤立的最低位1,则将该位升一位,例如:1001 -> 1010

如果末位1是连续的,则连续末位1的最高位升一位,其余位降到最低,例如:1001110->1010011

-----------------------------------------------------

代码 

#include<iostream>
#include<vector>
using namespace std;

const int NMAX = 100;

int main()
{
	int n,n1,i,len,high;
	bool bin;
	while (cin >> n)
	{
		if (n==0)
		{
			break;
		}
		n1 = n;
		i=0;
		vector<int> ones;							// 记录二进制中1的位置
		while (n>0)									// 十进制转二进制
		{
			bin = n - ((n>>1)<<1);
			n = n>>1;
			if (bin)
			{
				ones.push_back(i);
			}
			i++;
		}
		len = ones.size();
		if (len==1)									// 如果只有一个1
		{
			cout << (n1<<1) << endl;
			continue;
		}
		if (ones.at(1) > ones.at(0)+1)				// 如果最低位1是孤立的
		{
			cout << n1-(1<<ones.at(0))+(1<<(ones.at(0)+1)) << endl;
			continue;
		}
		for (i=0; i<len-1; i++)
		{
			if (ones.at(i+1)-ones.at(i) > 1)
			{
				break;
			}
		}
		high = i;									// 从最低位1开始连续是1的最高位
		for (i=0; i<high; i++)
		{
			n1 -= (1<<ones.at(i));
			n1 += (1<<i);
		}
		n1 -= (1<<ones.at(high));
		n1 += (1<<(ones.at(high)+1));
		cout << n1 << endl;
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/da_kao_la/article/details/80756800
今日推荐