คำอธิบายปัญหา
เรารู้ว่าหมายเลขคอลัมน์ Excel เป็นตัวอักษร เริ่มจาก A และหลัง Z จะเป็น AA, AB, จนถึง ZZ แล้วค่อยเป็น AAA, AAB, จนถึง ZZZ และต่อไปเรื่อยๆ ดังนั้นคอลัมน์ 1 คือ A คอลัมน์ 27 คือ Z ที่นี่เราจะดูวิธีหาตัวอักษรคอลัมน์ถ้ารู้หมายเลขคอลัมน์ เช่นถ้าหมายเลขคอลัมน์คือ 80 จะได้ CB
สมมติว่าเรามีตัวเลข n ค่าเป็น 28 เราต้องหาเศษกับ 26 ถ้าเศษเป็น 0 หมายถึงเลข 26, 52 เป็นต้น เราจะใส่ Z ในสตริงผลลัพธ์ ค่า n จะกลายเป็น n/26 – 1 และถ้าเศษไม่เป็นศูนย์ เราแค่แทรกตัวอักษรที่ตรงกันเข้าไปในสตริง และทำ n = n/26 สุดท้าย พิมพ์สตริงกลับด้าน (reverse)
ตัวอย่างโค้ด (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.begin() + str.length()); cout << str << endl; } int main() { int n = 700; cout << "Cell name of " << n << " is: "; showColumnLetters(700); }นำเข้า
Cell number: 700
ผลลัพธ์
Enter cell number:700 Cell name of 700 is: ZX