LeetCode Excel Sheet Column Title
Problem
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
即生成Excel表格的表头
Python 实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# 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
# author li.hzh
class Solution:
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
remainder, result = 0, ""
while n > 26:
remainder = (n - 1) % 26
n = (n - 1) // 26
result = (chr(65 + remainder)) + result
result = (chr(64 + n)) + result
return result
solution = Solution()
print(solution.convertToTitle(1))
print(solution.convertToTitle(26))
print(solution.convertToTitle(27))
print(solution.convertToTitle(30))
print(solution.convertToTitle(52))
print(solution.convertToTitle(53))
print(solution.convertToTitle(54))
print(solution.convertToTitle(676))
print(solution.convertToTitle(677))
print(solution.convertToTitle(702))
print(solution.convertToTitle(703))
print(solution.convertToTitle(728))
分析
讲不出太多道理,分析出Excel表头生成的规律,直接计算即可。
所有代码已上传至Github:https://github.com/lihongzheshuai/yummy-code
GESP 学习专题站:GESP WIKI
"luogu-"系列题目可在洛谷题库进行在线评测。
"bcqm-"系列题目可在编程启蒙题库进行在线评测。
欢迎加入:Java、C++、Python技术交流QQ群(982860385),大佬免费带队,有问必答
欢迎加入:C++ GESP/CSP认证学习QQ频道,考试资源总结汇总
欢迎加入:C++ GESP/CSP学习交流QQ群(688906745),考试认证学员交流,互帮互助
本文由作者按照 CC BY-NC-SA 4.0 进行授权
