文章

LeetCode Excel Sheet Column Number

Problem

Related to question Excel Sheet Column Title

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

1
2
3
4
5
6
7
    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 

即从Excel列头计算出列序号

Python 实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# 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

# author li.hzh
class Solution:
    def titleToNumber(self, s):
        """
        :type s: str
        :rtype: int
        """
        result = 0
        for val in s:
            result = result * 26 + ord(val) - 64
        return result


solution = Solution()
print(solution.titleToNumber("A"))
print(solution.titleToNumber("Z"))
print(solution.titleToNumber("BZ"))
print(solution.titleToNumber("ZZ"))
print(solution.titleToNumber("AAA"))

分析

这个就简单多了,就是26进制转10进制。

本文由作者按照 CC BY 4.0 进行授权