C语言L1-033 出生年
时间: 2025-02-19 21:28:34 浏览: 68
### C语言 L1-033 出生年 题目解析
#### 输入描述
输入在一行中给出两个整数 y 和 n,中间以空格分隔。y 表示出生年份,在区间 [1, 3000] 之间;n 是目标年份中不同数字的个数,可以是 2 或者 3 或者 4。
#### 输出描述
对于给定的出生年份 y 及其对应的 n 值,计算并输出该人在多少岁时遇到了第一个满足条件的目标年份。如果到公元 3000 年为止都没有找到这样的年份,则输出 "Impossible!"。
#### 示例代码实现
下面是一个完整的解决方案来解决这个问题:
```c
#include <stdio.h>
#include <stdbool.h>
// 判断某一年是否有指定数量的不同数字
bool hasDistinctDigits(int year, int distinctCount) {
bool digits[10] = {false};
int count = 0;
while (year > 0) {
int digit = year % 10;
if (!digits[digit]) {
digits[digit] = true;
++count;
}
year /= 10;
}
// 处理小于四位的情况
for (int i = 0; i < 4 && count < distinctCount; ++i) {
if (!digits[i])
++count;
}
return count >= distinctCount;
}
int main() {
int birthYear, targetDigitCount;
scanf("%d%d", &birthYear, &targetDigitCount);
for (int age = 0;; ++age) {
int currentYear = birthYear + age;
if (currentYear > 3000 || hasDistinctDigits(currentYear, targetDigitCount)) {
if (currentYear <= 3000)
printf("%d\n", age);
else
puts("Impossible!");
break;
}
}
return 0;
}
```
此段代码实现了对特定条件下年龄的求解过程[^3]。通过 `hasDistinctDigits` 函数检测每一年是否含有足够的独特数字,并以此为基础遍历可能的结果直至找到符合条件的第一年或超出范围停止循环。
阅读全文
相关推荐



