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ụ n=80 → CB.
Giải pháp: lấy n chia 26 lấy dư. Nếu dư=0 thì là Z, n = n/26 - 1. Nếu dư≠0 thì ký tự = (dư-1)+'A', n = n/26. Đảo ngược chuỗi kết quả.
Ví dụ mã nguồn
#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ả đầu ra
Cell name of 700 is: ZX