ภาพรวมปัญหา
ได้รับ L, R, และ d ต้องพิมพ์ Good Numbers ในช่วง L ถึง R ที่ไม่มีหลัก d
Good Number คืออะไร?
ตัวเลขที่ทุกหลักมีค่ามากกว่าผลรวมของหลักที่อยู่ทางขวา (น้อยกว่า) เช่น 732: 7 > 3+2 และ 3 > 2
ตัวอย่าง
Input: L = 400, R = 500, k = 3 Output: 410, 420, 421
Good numbers ระหว่าง 400-500: 410, 420, 421, 430 แต่ 430 มีหลัก 3 จึงไม่พิมพ์
วิธีแก้ปัญหา
- ลูปตรวจสอบทุกตัวเลขในช่วง L ถึง R
- ตรวจสอบว่าเป็น Good Number และไม่มีหลัก d
- ตรวจสอบ Good Number: วิ่งจากหลักหน่วยไปซ้าย รักษาผลรวม หลักถัดไปต้อง > ผลรวม
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
bool isvalidNumber(int n, int d) {
int digit = n % 10;
int sum = digit;
if (digit == d) return false;
n /= 10;
while (n) {
digit = n % 10;
if (digit == d || digit <= sum)
return false;
else {
sum += digit;
n /= 10;
}
}
return true;
}
void printGoodNumbersLtoR(int L, int R, int d) {
for (int i = L; i <= R; i++) {
if (isvalidNumber(i, d))
cout << i << " ";
}
}
int main() {
int L = 400, R = 600, d = 3;
cout << "All good numbers from " << L << " to " << R << " that do not contain " << d << " are:\n";
printGoodNumbersLtoR(L, R, d);
return 0;
}
ผลลัพธ์ (Output)
All good numbers from 400 to 600 that do not contain 3 are: 410 420 421 510 520 521 540