问题描述:
给定一个Excel表格中的列名称,返回其相应的列序号。
例如,
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
示例 1:
输入: "A" 输出: 1
示例 2:
输入: "AB" 输出: 28
示例 3:
输入: "ZY" 输出: 701
方法1:(转)
1 class Solution(object): 2 def titleToNumber(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 sum_ = 0 8 for i in range(len(s)): 9 tmp = ord(s[i]) - 65 + 1 10 sum_ = tmp + 26 * sum_ 11 return sum_
ABC = step1:sum_ = 1 + 26 × 0 ;step2:sum_ = 2 + 26 × 1;step3: sum_ = 3 + 26 × 28
方法2:(转)
1 class Solution(object): 2 def get_int(self,strs): 3 return ord(strs) - 64 4 5 def titleToNumber(self, s): 6 """ 7 :type s: str 8 :rtype: int 9 """ 10 result = 0 11 s = s[::-1] 12 for i in range(len(s)): 13 if i==0: 14 result +=self.get_int(s[i]) 15 else: 16 result += 26**i*self.get_int(s[i]) 17 return result
ABC ->CBA = 3 + 26^1×2 + 26^2×1
2018-09-15 10:03:08