1. 程式人生 > >Lucky Numbers (easy)(模擬,字典序全排列)

Lucky Numbers (easy)(模擬,字典序全排列)

B. Lucky Numbers (easy) time limit per test 2 seconds memory limit per test 256 megabytes input standard input output standard output

Petya loves lucky numbers. Everybody knows that positive integers are lucky if their decimal representation doesn't contain digits other than 4 and 7. For example, numbers 477444 are lucky and 517467 are not.

Lucky number is super lucky if it's decimal representation contains equal amount of digits 4

 and 7. For example, numbers 477744,474477 are super lucky and 4744467 are not.

One day Petya came across a positive integer n. Help him to find the least super lucky number which is not less than n.

Input

The only line contains a positive integer n (1 ≤ n ≤ 109). This number doesn't have leading zeroes.

Output

Output the least super lucky number that is more than or equal to n.

Please, do not use the %lld specificator to read or write 64-bit integers in C++. It is preferred to use the cin, cout streams or the %I64d specificator.

Examples input
4500
output
4747
input
47
output
47

註釋寫的挺全的。看程式碼吧。

程式碼如下:

#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
using namespace std;
void pr(int l)
{
	for (int i = 1 ; i <= l ; i++)
		printf ("4");
	for (int i = 1 ; i <= l ; i++)
		printf ("7");
	printf ("\n");
}
int main()
{
	char a[15];
	char t[15];
	int i;
	int l;		//位數 
	scanf ("%s",a);
	l = strlen(a);
	if (l & 1)		//l為奇數時,擴充一位就行 
	{
		l = (l + 1) >> 1;
		pr(l);
	}
	else
	{
		for (i = 0 ; i < (l / 2) ; i++)		//先構造最大的 
			t[i] = '7';
		for ( ; i < l ; i++)
			t[i] = '4';
		int r = strcmp(a , t);
		if (r == 1)
			pr ((l + 2) >> 1);
		else
		{
			for (i = 0 ; i < (l / 2) ; i++)		//再從最小的開始 
				t[i] = '4';
			for ( ; i < l ; i++)
				t[i] = '7';
			do
			{
				r = strcmp(a , t);
				if (r == 0 || r == -1)		//比它小,就輸出,否則字典序遞增
				{
					for (i = 0 ; i < l ; i++)		//為什麼t[i]!='\0'提交到cf就多了個@呢!! 
						printf ("%c",t[i]);
					printf ("\n");
					break;
				}
			}while (next_permutation(t , t + l));
		}
	}
	return 0;
}