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])
总体来说第一种方法速度比第二种要快。