Chuyển số nguyên dương thành tiêu đề cột Excel: 1→A, 2→B, ..., 26→Z, 27→AA, 28→AB, ...
Ví dụ: 3→C, 27→AA, 151→EU.
Giải thuật
- Đây là hệ cơ số 26 nhưng không có chữ số 0 (1-based)
- Lặp: lấy (n-1)%26 → ký tự 'A'+..., n = (n-1)/26, cho đến n=0
- Đảo ngược chuỗi kết quả
Chương trình
#include <stdio.h>
#include <stdlib.h>
static char *convert_To_Excel_Title(int column_no) {
if (column_no <= 0) return "";
char *result = malloc(1024);
int len = 0;
do {
result[len++] = ((column_no - 1) % 26) + 'A';
column_no = (column_no - 1) / 26;
} while (column_no > 0);
result[len] = '\0';
// Đảo chuỗi
for (int i = 0, j = len - 1; i < j; i++, j--) {
char c = result[i]; result[i] = result[j]; result[j] = c;
}
return result;
}
int main(void) {
int n;
for (int t = 0; t < 3; t++) {
printf("enter integer: "); scanf("%d", &n);
printf("Column %d -> %s\n", n, convert_To_Excel_Title(n));
}
return 0;
}
Kết quả
enter integer1: 23 → W enter integer2: 12 → L enter integer3: 69 → BQ