leetcode-168-Excel-Sheet-Column-Title

描述


Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

1
2
3
4
5
6
7
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB

分析


10进制转26进制,和(E) Excel Sheet Column Number 是互逆的。

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
string convertToTitle(int n) {
if(n < 1) {
return "";
}else {
string result = "";
while(n) {
n--;
result = char(n%26 + 'A') + result;
n /= 26;
}
return result;
}
}
};

解决方案2(Python)


1
2
3
4
5
6
7
8
9
10
11
12
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = []
while n:
n -= 1
result.insert(0, chr(ord('A')+n%26))
n /= 26
return "".join(result)

相关问题


(E) Excel Sheet Column Number

题目来源