Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Count Hexadecimal Number: นับตัวเลขฐานสิบหกในช่วงใน C++

ปัญหา

กำหนดช่วง [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 ตัว

แนวคิด

  1. ตัวเลข 10-15: เป็น Hex Digit เดียว → นับ 1 ต่อตัว
  2. ตัวเลข > 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)

RangeHex Digits FoundCount
10-15A,B,C,D,E,F6
16-3110,11,12,13,14,15,16,17,18,19,1A,1B,1C,1D,1E,1F10 (A-F ในหลักหน่วย)
32-4720-2F10 (A-F ในหลักหน่วย)
48-6030-3C3 (A,B,C ในหลักหน่วย)
Total21

ความซับซ้อน

  • 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