该系列题目取自 LeetCode 精选 TOP 面试题列表:https://leetcode-cn.com/problemset/top/
LeetCode 171. Excel 表列序号:https://leetcode-cn.com/problems/excel-sheet-column-number/
给定一个 Excel 表格中的列名称,返回其相应的列序号。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
输入: "A"
输出: 1
示例 2:
输入: "AB"
输出: 28
示例 3:
输入: "ZY"
输出: 701
通过观察可知,这道题的本质其实是 26 进制转 10 进制的计算。
A~Z 共 26 个字母,各字母对应数字关系如下:
与其他进制转 10 进制的计算方式相同。我们假设 n 位上的数字为 ,那么该位置所产生的 10 进制数值为:
最终的 10 进制结果即为各个位上所产生的数值之和。
以题目中给出的 "ZY"
为例:
class Solution:
def titleToNumber(self, s: str) -> int:
res = 0
ans = 1
for word in s[::-1]:
res += ans * (ord(word) - ord('A') + 1)
ans *= 26
return res
func titleToNumber(s string) int {
res := 0
length := len(s)
ans := 1
for i := 0; i < length; i++ {
index := length - i - 1
res += ans * (int(s[index]) - int('A') + 1)
ans *= 26
}
return res
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有