在 C++ 中打印一个严格小于给定数字的数字,并且其所有数字都不同
在这个问题中,我们给定一个数字 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP