ภาพรวมปัญหา
ได้รับตัวเลข n ต้องพิมพ์ตัวเลขที่มากที่สุดแต่น้อยกว่า n ที่มีหลักต่างกันทั้งหมด (ไม่มีเลขซ้ำ)
ตัวอย่าง
Input: n = 2332 Output: 2319
วิธีแก้ปัญหา
นับถอยหลังจาก n-1 ลงมา 0 ตรวจสอบแต่ละตัวว่าเป็น distinct digits หรือไม่ พบแล้วพิมพ์และหยุด
ตัวอย่างโค้ด C++
#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;
}
return -1;
}
int main() {
int n = 44324;
cout << "Number less than " << n << " with all digits distinct are: "
<< findDistinctDigitNumber(n);
return 0;
}
ผลลัพธ์ (Output)
Number less than 44324 with all digits distinct are: 43987