题目链接
https://leetcode.com/problems/excel-sheet-column-number/
题目原文
Given a column title as appear in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
…
Z -> 26
AA -> 27
AB -> 28
题目翻译
给定一个Excel表格中的列标题,求其对应的列数字。比如:
A -> 1
B -> 2
C -> 3
…
Z -> 26
AA -> 27
AB -> 28
思路方法
首先,我们要知道Excel里这个对应关系是什么样的。从A-Z对应1-26,当列标题进一位变成AA时,列对应的数字变成27,这本质上是一个26进制转10进制的问题,不过A对应的是1而不是0,要注意。
既然问题被转化了就解决了,那么接下来,我们尝试一下写出不同的Python代码吧。
代码一
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
sum = 0
for c in s:
sum = sum*26 + ord(c) - 64 # 64 = ord('A') - 1
return sum
用map和reduce。
代码二
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
return reduce(lambda x,y: x*26 + y, map(lambda x:ord(x)-64, s), 0)
用自带的进制转换函数,不过要小心这里有两个陷阱:1,这里的26进制是从A开始而不是0;2,A对应的是1。
代码三
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
sum = 0
for c in s:
sum = sum* 26 + int(c, 36) - 9
return sum
相关题目:168. Excel Sheet Column Title
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:http://blog.youkuaiyun.com/coder_orz/article/details/51406455