题目:
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
题解:
想明白了就容易了。 求base-26的表达式,用A~Z表示。
由低位向高位计算。计算每一位的计算公式为: 'A' + (n - 1) % 26
n = (n - 1) / 26
C++版:
class Solution {
public:
string convertToTitle(int n) {
string result = "";
while(n > 0) {
result = (char)('A' + (n - 1) % 26) + result;
n = (n - 1) / 26;
}
return result;
}
};
Java版:
public class Solution {
public String convertToTitle(int n) {
StringBuffer sb = new StringBuffer();
while(n > 0) {
sb.insert(0, (char)('A' + (n - 1) % 26));
n = (n - 1) / 26;
}
return sb.toString();
}
}
Python版:
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
result = ""
while n > 0:
result = chr(ord("A") + (n - 1) % 26) + result
n = (n - 1) / 26
return result