您的位置:首页 > 其它

LeetCode 168 Excel Sheet Column Title

2017-05-04 12:37 381 查看
168. Excel Sheet Column Title

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


难度EASY。相当于是26进制转换,稍微做点处理。

class Solution {
public:
string convertToTitle(int n) {
string s = "";
while(n)
{
int x = --n % 26;
s += 'A' + x;
n /= 26;
}
reverse(s.begin(),s.end());
return s;
}
};


还有一种更简单的写法,避免用Reverse,直接利用递归栈的思想。

如下:

class Solution {
public:
string convertToTitle(int n) {
return n == 0 ? "" : convertToTitle(n / 26) + (char) (--n % 26 + 'A');
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 168 Excel-Shee