แนวคิด
สมมติว่ามีจำนวนเต็มบวก ให้หาชื่อคอลัมน์ที่สอดคล้องกันใน Excel ดังนี้ [1: A], [2: B], [26: Z], [27: AA], [28: AB] เป็นต้น
เช่น ถ้าอินพุตคือ 28 ผลลัพธ์คือ AB
วิธีแก้:
- while n ไม่เป็นศูนย์:
- n := n - 1
- res := res + n mod 26 + ASCII ของ 'A'
- n := n / 26
- กลับลำดับอาร์เรย์ res
- คืนค่า res
ตัวอย่าง
#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;
}
};
main() {
Solution ob;
cout << (ob.convertToTitle(30));
}
อินพุต
30
เอาต์พุต
AD