Excel Sheet Column Number

题目描述

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

解题方法

这一题的解法是将每一个独立的字母分开来看,相同于这是一个26进制的数, 每一个字母的number通过与A的ascii码的差来得到。

Solution

class Solution(object):
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0

        length = len(s)
        result = 0
        for i in range(length):
            result = result * 26 + ord(s[i]) - ord('A') + 1

        return result

Reference