ปัญหา
กำหนดช่วง [start, end] นับจำนวน Hexadecimal Digits (A-F) ที่ปรากฏในตัวเลขทุกตัวในช่วงนี้
Hexadecimal: 0-9, A(10), B(11), C(12), D(13), E(14), F(15)
ตัวอย่าง: start=10, end=13 → 10=A, 11=B, 12=C, 13=D → 4 ตัว
แนวคิด
- ตัวเลข 10-15: เป็น Hex Digit เดียว → นับ 1 ต่อตัว
- ตัวเลข > 15: แปลงเป็น Base-16 แล้วนับ Digit ที่ ≥ 10 (A-F) ในแต่ละตำแหน่ง
โค้ด C++
#include <iostream>
using namespace std;
int countHexa(int start, int end) {
int result = 0;
for (int i = start; i <= end; i++) {
// กรณี 10-15: นับ 1 ต่อตัว
if (i >= 10 && i <= 15) {
result++;
}
// กรณี > 15: แปลง Base-16 นับ Digit A-F
else if (i > 15) {
int k = i;
while (k != 0) {
if (k % 16 >= 10) { // Digit เป็น A-F
result++;
}
k = k / 16;
}
}
}
return result;
}
int main() {
int start = 10, end = 60;
cout << "count is: " << countHexa(start, end); // 21
return 0;
}
การทำงานตัวอย่าง (10-60)
| Range | Hex Digits Found | Count |
|---|---|---|
| 10-15 | A,B,C,D,E,F | 6 |
| 16-31 | 10,11,12,13,14,15,16,17,18,19,1A,1B,1C,1D,1E,1F | 10 (A-F ในหลักหน่วย) |
| 32-47 | 20-2F | 10 (A-F ในหลักหน่วย) |
| 48-60 | 30-3C | 3 (A,B,C ในหลักหน่วย) |
| Total | 21 |
ความซับซ้อน
- Time: O((end-start+1) × log₁₆(end)) ≈ O(N log N)
- Space: O(1)
Input / Output
Input: start=10, end=60
Output: count is: 21