LeetCode Excel Sheet Column Title

所属专题核心算法
核心标签LeetCode
代码 / 阅读C++11 · 3 min
累计阅读实时统计
TL;DR · 核心摘要

Problem Given a positive integer, return its corresponding column title as appear in an Excel sheet. For example: 即生成Excel表格的表头 Python...

Problem

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

For example:

Code· 7 行
    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB

即生成Excel表格的表头

Python 实现

Python· 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表头生成的规律,直接计算即可。

OneCoder 信奥远征平台 · oi.coderli.com

看完题解,马上用 240 关实战检验掌握度

覆盖 GESP 1~8 级考纲心法、CSP-J 双栏阅读程序、错题动态变式推演与 90/120 分钟全真模考。

立即闯关
开源代码与考纲字典

配套题解代码归档于 yummy-code 仓库,完整知识点索引见 GESP Wiki。

技术交流与考级答疑

欢迎加入 C++ GESP/CSP 群(688906745) 或 Java/Python 群(982860385)。

同专栏相关推荐

OneCoder

OneCoder

始于 2012

持续记录 C++ GESP/CSP 信奥算法、Java 服务端架构与 Python 工程实战。官方唯一域名:coderli.com

读者讨论与留言

共 0 条讨论
邮箱仅用于接收回复通知,不对外展示
还没有读者留言,欢迎写下你的第一条交流笔记。