题目
excel-sheet-column-title
算法
* 直接模拟
* 直接模拟优化
* 递归
代码
* 直接模拟
class Solution {
public:
string convertToTitle(int n) {
string res = "";
while (n) {
if (n % 26 == 0) {
res += 'Z';
n -= 26;
}
else {
res += n%26 - 1 + 'A';
n -= n%26;
}
n /= 26;
}
reverse(res.begin(), res.end());
return res;
}
};
* 优化
class Solution {
public:
string convertToTitle(int n) {
string res;
while (n) {
res += --n % 26 + 'A';
n /= 26;
}
return string(res.rbegin(), res.rend());
}
};
* 递归
class Solution {
public:
string convertToTitle(int n) {
return n == 0 ? "" : convertToTitle(n / 26) + (char)(--n % 26 + 'A');
}
};