171. Excel Sheet Column Number Leetcode Python
阿新 • • 發佈:2019-02-07
Related to question Excel Sheet Column Title
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
Credits:
recursive:
總體來說第一種方法速度比第二種要快。
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
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
這題可以當作求26進位制數來做。 可以用iterative的方法也可以用遞迴的方法來做
iterative:
class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
result=0
n=len(s)
for i in range(n):
result=result*26+ord(s[i])-64
return result
recursive:
class Solution: # @param s, a string # @return an integer def titleToNumber(self, s): if len(s)==1: return ord(s)-64 return ord(s[-1])-64+26*self.titleToNumber(s[:-1])
總體來說第一種方法速度比第二種要快。