171_Excel Sheet Column Number

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 
...

Example 1:

Input: "A"

Output: 1

Example 2:

Input: "AB"

Output: 28

Example 3:

Input: "ZY"

Output: 701

Solution:

Idea:

  • This problem is basically the problem of converting a string representing a base 26 number to the corresponding integer.

  • Note that "A" correspond to 1 not 0.

Code 1: Iterative approach

def titleToNumber(s):
    """
    :type s: str
    :rtype: int
    """
    output = 0
    for i in s:
        output = output * 26 + ord(i) - ord("A") + 1
    return output

Code 2: Recursive approach

def titleToNumber(s):
    """
    :type s: str
    :rtype: int
    """
    if len(s) == 1:
        return ord(s[-1]) - ord("A") + 1
    return titleToNumber(s[:-1]) * 26 + ord(s[-1]) - ord("A") + 1

Last updated