Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Số cột Excel từ số thứ tự trong C++


Cột Excel dùng chữ cái: A, B, ..., Z, AA, AB, ..., ZZ, AAA,... Cột 1=A, cột 27=AA. Cho số cột n, tìm tên cột. Ví dụ: 80 → CB.

Thuật toán

  1. Lấy dư n % 26
  2. Nếu dư = 0: ký tự 'Z', n = n/26 - 1
  3. Nếu dư ≠ 0: ký tự = (dư-1) + 'A', n = n/26
  4. Lặp cho đến n=0
  5. Đảo ngược chuỗi kết quả

Chương trình C++

#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);
}

Kết quả

Cell name of 700 is: ZX

Ví dụ thêm

  • 1 → A
  • 26 → Z
  • 27 → AA
  • 52 → AZ
  • 701 → ZY