首页 文章资讯内容详情

打印一个严格小于给定数字的数字,以便其所有数字在C ++中都是不同的

2026-06-04 1 花语

在这个问题上,给我们一个数字n。我们的任务是打印小于n的最大数字,以使所有数字都不同。

让我们以一个例子来了解问题

Input: n = 2332 Output: 2319

为了解决这个问题,我们将数字的计数从n反转为0。如果当前计数值满足条件,则检查数字是否不同,并打印循环并结束循环。否则继续循环。循环运行的最大次数始终小于n。

示例

实施我们的解决方案的程序,

#include <bits/stdc++.h> using namespace std; int findDistinctDigitNumber(int n) { for (int i = n - 1; i>=0 ; i--) { int count[10] = { 0 }; int x = i; int count1 = 0, count2 = 0; while (x) { count[x % 10]++; x /= 10; count1++; } for (int j = 0; j < 10; j++) { if (count[j] == 1) count2++; } if (count1 == count2) return i; } } int main() { int n = 44324; cout<<"Number less than "<<n<<" with all digits distinct are : "<<findDistinctDigitNumber(n); return 0; }

输出结果

Number less than 44324 with all digits distinct are : 43987