题目链接
https://leetcode.com/problems/excel-sheet-column-title/
题目原文
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
给定一个正整数,返回其在Excel表格中作为列序号时对应的列标题。For example:
1 -> A
2 -> B
3 -> C
…
26 -> Z
27 -> AA
28 -> AB
题目翻译
给定一个正整数,返回其在Excel表格中作为列序号时对应的列标题。比如:
1 -> A
2 -> B
3 -> C
…
26 -> Z
27 -> AA
28 -> AB
思路方法
首先,我们要知道Excel里这个对应关系是什么样的。从A-Z对应1-26,当列标题进一位变成AA时,列对应的数字变成27。所以这个题本质上是一个10进制转26进制的问题,不过A对应的是1而不是0,要注意。
思路一
用处理进制转换的一般思路,重复取模和除法即可。但是注意由于A对应1,所以Z之后是AA,这个转换不同于一般的进制转换。
代码
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
res = ''
while n:
res = chr((n-1)%26 + 65) + res
n = (n-1) / 26
return res
思路二
与上面的思路类似,但采用递归来实现。
代码
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
if n == 0:
return ''
return self.convertToTitle((n-1)/26) + chr((n-1)%26 + 65)
相关问题:171. Excel Sheet Column Number
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51406627