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

โปรแกรมหาหมายเลขคอลัมน์สเปรดชีตจากชื่อคอลัมน์ใน C++

ภาพรวมปัญหา

ให้ชื่อคอลัมน์สเปรดชีต (เช่น A, B, ..., Z, AA, AB, ..., ZZ, AAA...) ต้องการหาหมายเลขคอลัมน์ที่สอดคล้อง

นี่คือระบบเลขฐาน 26 (Bijective Base-26) โดย A=1, B=2, ..., Z=26, AA=27, AB=28...

ตัวอย่าง

Input: 700

Output: ZX

คำอธิบาย: คอลัมน์ที่ 700 คือ ZX

หลักการแปลง (Base-26 ไม่มีศูนย์)

ต่างจากฐาน 26 ปกติที่มีตัวเลข 0-25 ระบบนี้ใช้ 1-26

  • n = 26 → Z (ไม่ใช่ A0)
  • n = 27 → AA (1,1)
  • อัลกอริทึม: n-- ก่อน แล้ว mod 26, div 26

โค้ดตัวอย่าง

#include <iostream>
#include <algorithm>
using namespace std;

void showColumnLetters(int n) {
    string str = "";
    while (n) {
        int rem = n % 26;
        if (rem == 0) {
            str += 'Z';
            n = (n / 26) - 1;
        } else {
            str += (rem - 1) + 'A';
            n = n / 26;
        }
    }
    reverse(str.begin(), str.end());
    cout << str << endl;
}

int main() {
    int n = 700;
    cout << "Cell name of " << n << " is: ";
    showColumnLetters(700);
    return 0;
}

ผลลัพธ์

Cell name of 700 is: ZX

วิธีที่เข้าใจง่ายกว่า (Standard Algorithm)


string convertToTitle(int n) {
    string res;
    while (n > 0) {
        n--; // ปรับให้ 0-based
        res += 'A' + (n % 26);
        n /= 26;
    }
    reverse(res.begin(), res.end());
    return res;
}

การทดสอบ

NumberColumn
1A
26Z
27AA
28AB
52AZ
53BA
700ZX
701ZY
702ZZ
703AAA

ความซับซ้อน

  • เวลา: O(log₂₆ N) — จำนวนหลักของผลลัพธ์
  • พื้นที่: O(log₂₆ N) — สำหรับเก็บ string ผลลัพธ์