ภาพรวมปัญหา
ให้หมายเลขคอลัมน์ (จำนวนเต็มบวก) ต้องการหาชื่อคอลัมน์สเปรดชีตที่สอดคล้อง เช่น 1→A, 26→Z, 27→AA, 28→AB
ตัวอย่าง
Input: 30
Output: AD
หลักการแปลง (เหมือน xID 1004079061)
ระบบ Bijective Base-26: ไม่มีเลข 0, ใช้ A=1 ถึง Z=26
อัลกอริทึมมาตรฐาน:
- n-- (ปรับเป็น 0-based)
- res += 'A' + (n % 26)
- n /= 26
- ทำซ้ำจน n == 0
- reverse ผลลัพธ์
โค้ดตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
string convertToTitle(int n) {
string res;
while (n) {
res += (--n) % 26 + 'A';
n /= 26;
}
reverse(res.begin(), res.end());
return res;
}
};
int main() {
Solution ob;
cout << ob.convertToTitle(30);
return 0;
}
ผลลัพธ์
AD
การทำงานทีละขั้น (n=30)
- n=30: n--=29, 29%26=3 → 'D', n=29/26=1, res="D"
- n=1: n--=0, 0%26=0 → 'A', n=0/26=0, res="DA"
- reverse → "AD" ✓
ฟังก์ชันย้อนกลับ (Column Title → Number)
int titleToNumber(string s) {
int result = 0;
for (char c : s) {
result = result * 26 + (c - 'A' + 1);
}
return result;
}
ความซับซ้อน
- เวลา: O(log₂₆ N)
- พื้นที่: O(log₂₆ N)
ความแตกต่างจาก xID 1004079061
xID 1004079061: Input = หมายเลขคอลัมน์ (700) → Output = ชื่อคอลัมน์ (ZX)
xID 1004079062: Input = หมายเลขคอลัมน์ (30) → Output = ชื่อคอลัมน์ (AD)
ทั้งสองคือปัญหาเดียวกัน แค่ตัวอย่างตัวเลขต่างกัน