LeetCode 题解工作台
Excel 表列名称
给你一个整数 columnNumber ,返回它在 Excel 表中相对应的列名称。 例如: A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ... 示例 1: 输入: columnNumber = 1 输出: "A" 示例 2: 输入: col…
2
题型
6
代码语言
3
相关题
当前训练重点
简单 · 数学·string
答案摘要
class Solution: def convertToTitle(self, columnNumber: int) -> str:
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·string 题型思路
题目描述
给你一个整数 columnNumber ,返回它在 Excel 表中相对应的列名称。
例如:
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
示例 1:
输入:columnNumber = 1 输出:"A"
示例 2:
输入:columnNumber = 28 输出:"AB"
示例 3:
输入:columnNumber = 701 输出:"ZY"
示例 4:
输入:columnNumber = 2147483647 输出:"FXSHRXW"
提示:
1 <= columnNumber <= 231 - 1
解题思路
方法一
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
res = []
while columnNumber:
columnNumber -= 1
res.append(chr(ord('A') + columnNumber % 26))
columnNumber //= 26
return ''.join(res[::-1])
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | O(\log N) |
| 空间 | O(1) |
面试官常问的追问
外企场景- question_mark
The interviewer may hint at off-by-one errors when handling 'Z'.
- question_mark
Expect questions on handling large column numbers efficiently without recursion.
- question_mark
They may ask you to explain how base-26 mapping differs from standard decimal conversion.
常见陷阱
外企场景- error
Forgetting to subtract 1 before modulo leads to incorrect letters for multiples of 26.
- error
Prepending letters incorrectly can reverse the title and yield wrong results.
- error
Not handling large numbers properly can cause overflow if intermediate calculations assume 32-bit limits.
进阶变体
外企场景- arrow_right_alt
Return the column title in lowercase letters instead of uppercase.
- arrow_right_alt
Given a list of columnNumbers, return all corresponding Excel titles in one pass.
- arrow_right_alt
Implement the inverse function converting Excel titles back to integers.