题目链接 : 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进制转十进制
class Solution:
def titleToNumber(self, s: str) -> int:
res = 0
bit = 1
for a in s[::-1]:
res += (ord(a) - 64) * bit
bit *= 26
return res
或者一行代码
import functools
class Solution:
def titleToNumber(self, s: str) -> int:
return functools.reduce(lambda x, y: x * 26 + y, [ord(a) - 64 for a in s ])
再或者
class Solution:
def titleToNumber(self, s: str) -> int:
return sum( (ord(a) - 64) * (26 ** i) for i, a in enumerate(s[::-1]))