ในปัญหานี้ เราได้รับตัวเลข 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