problem
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
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
solution
和171题相反
和一般26进制不同的是,每一位取值范围是[1,26]而不是[0,25]
所以当0出现的时候的要特殊处理,当前位使用26,更高位减1
divmod(a,b)方法返回的是a//b(除法取整)以及a对b的余数
返回结果类型为tuple
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
azStr = ''
while n != 0:
n,remainder = divmod(n,26)
if remainder:
azStr += chr(remainder+64)
else:
azStr += chr(26 + 64)
n = n-1
return azStr[::-1]
- n-1 能否避开0的特殊情况?
- 当前+的是64
- 对于余数,如果n-1 应该是加65(A)
- 对于除数结果,只有当n等于26的倍数时-1的结果才有变化,但此时个位为26(Z),本来就应该少进一位(除数结果需要-1),所以n-1处理结果正确
(即当n为26倍数的时候,要么n/26 -1-- 上面解法,要么(n-1)/26--下面解法,结合余数的处理,选择下面的解法) - 修改如下
class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
azStr = ''
while n != 0 :
n,remainder = divmod(n-1,26)
azStr += chr(remainder+65)
return azStr[::-1]
discuss solution
使用了递归,求除数,求余数分别进行运算
return "" if num == 0 else self.convertToTitle((num - 1) / 26) + chr((num - 1) % 26 + ord('A'))