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 47, 744, 4 are lucky and 5, 17, 467 are not.
Lucky number is super lucky if it's decimal representation contains equal amount of digits 4 and 7. For example, numbers 47, 7744,474477 are super lucky and 4, 744, 467 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
4500output
4747input
47output
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;
}