在 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
廣告