前言
以上是新浪微博中一奇葩贴:“我出生于1988年,直到25岁才遇到4个数字都不相同的年份。”也就是说,直到2013年才达到“4个数字都不相同”的要求。本题请你根据要求,自动填充“我出生于y年,直到x岁才遇到n个数字都不相同的年份”这句话。
输入格式:
输入在一行中给出出生年份y和目标年份中不同数字的个数n,其中y在[1, 3000]之间,n可以是2、或3、或4。注意不足4位的年份要在前面补零,例如公元1年被认为是0001年,有2个不同的数字0和1。
输出格式:
根据输入,输出x和能达到要求的年份。数字间以1个空格分隔,行首尾不得有多余空格。年份要按4位输出。注意:所谓“n个数字都不相同”是指不同的数字正好是n个。如“2013”被视为满足“4位数字都不同”的条件,但不被视为满足2位或3位数字不同的条件。
输入样例1:
1988 4
输出样例1:
25 2013
输入样例2:
1 2
输出样例2:
0 0001
一、C语言解答
#include <stdio.h>
int FindCount(int x, int n);
int main()
{
int y, n;
int i, count = 0;
scanf("%d %d", &y, &n);
for (i = y; i < 3012; i++) //这是一个坑,题目中给的是y的年份,当y= 3000的时候,肯定还要往上便利,所以循环结束应至少设置为3013
{
if (FindCount(i, n) == 1)
{
break;
}
count++;
}
printf("%d %04d\n", count, i);
return 0;
}
//判断一个整数中是否有n个不同数字
int FindCount(int x, int n)
{
int count1 = 0, count2 = 0;
int temp, mod;
int i;
int a[10] = {0};
temp = x;
while (temp)
{
mod = temp % 10;
a[mod]++;
temp /= 10;
count1++;
}
if (count1 != 4)
{
a[0] += 4 - count1;
}
for (i = 0; i < 10; i++)
{
if (a[i] != 0)
{
count2++;
}
}
if (count2 == n)
{
return 1;
}
else
{
return 0;
}
}
二、Python解答
def dif_num_fun(strNum):
if len(strNum) < 4:
strNum = strNum.zfill(4)
countdict = dict()
for ch in strNum:
countdict[ch] = countdict.get(ch, 0) + 1
return len(countdict)
year, m = input().split()
count = 0
while (dif_num_fun(year) != int(m)):
year = str(int(year)+1)
count += 1
print("{0:} {1:}".format(count, year.zfill(4)))
总结
提示:通过str.zfill(width)可以实现将字符串按宽度width输出,不足自动在左侧补0,字符串长度大于或等于width则原样输出。也可使用str.rjust(width, ‘0’)来实现右对齐,不足补0