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

โปรแกรม C แปลงหมายเลขคอลัมน์ Excel เป็นชื่อคอลัมน์


คำอธิบายปัญหา

เขียนโปรแกรมแปลงหมายเลขคอลัมน์ (Integer) เป็นชื่อคอลัมน์ Excel เช่น 1→A, 2→B, ..., 26→Z, 27→AA, 28→AB, ฯลฯ

ตัวอย่าง

  • 3 → C
  • 27 → AA
  • 151 → EU

อัลกอริทึม

  1. ลบ 1 จาก column_no (เพราะ Excel เริ่มที่ 1 ไม่ใช่ 0)
  2. หาเศษจากการหาร 26 → ตัวอักษร (0=A, 25=Z)
  3. หาร column_no ด้วย 26
  4. ทำซ้ำจน column_no = 0
  5. กลับลำดับตัวอักษรที่ได้

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

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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';
    // กลับลำดับสตริง
    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() {
    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;
}

ผลลัพธ์

Enter integer: 23 → W
Enter integer: 12 → L
Enter integer: 69 → BQ