1.描述
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
2.分析
3.代码一
class Solution {
public:
string convertToTitle(int n) {
if (n <= 0) return "";
string title = "";
while (n > 26) {
unsigned int remaind = n % 26;
title.insert(title.begin(), remaind > 0 ? 'A' + n % 26 -1 : 'Z');
n /= 26;
n -= remaind > 0 ? 0 : 1;
}
unsigned int remaind = n % 26;
title.insert(title.begin(), remaind > 0 ? 'A' + n % 26 -1 : 'Z');
return title;
}
};
4.代码二
class Solution {
public:
string convertToTitle(int n) {
return n <= 0 ? "" : convertToTitle(n / 26) + (char) (--n % 26 + 'A');
}
};
网友评论