题目
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.
分析
按照Execl表格排列规律,求出给定正整数应该对应的字符串表示形式。
首先,我们需要建立一个map映射,保存1-26对应的字符;
然后,对给定的整数分析;
注意,当整数为26的倍数时需要特殊处理一下。
AC代码
class Solution {
public:
Solution()
{
for (int i = 1; i <= 26; ++i)
{
char c = 'A' + i - 1;
levelMap.insert({ i,c });
}//for
}
string convertToTitle(int n) {
if (n <= 0)
return "";
string str = "";
while (n)
{
if (n >= 1 && n <= 26)
{
str += levelMap[n];
reverse(str.begin(), str.end());
return str;
}
else{
if (n % 26 == 0)
{
str += 'Z';
n -= 26;
}
else
{
str += levelMap[n % 26];
}//else
n /= 26;
}
}
return str;
}
private:
map<int, char> levelMap;
};