Python Function to Convert Excel Sheet Column Titles to Numbers


microsoft-excel-03 Python Function to Convert Excel Sheet Column Titles to Numbers algorithms excel python

microsoft-excel-03

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

Constraints:
1 <= s.length <= 7
s consists only of uppercase English letters.
s is between “A” and “FXSHRXW”.

Compute the Excel Sheet Column Number using Python Iterative Function

The following is a simple Python function that takes a column title, and compute the base-26 numeric values. As the number starts from 1, we have to shift the value by one.

1
2
3
4
5
6
class Solution:
    def titleToNumber(self, s: str) -> int:
        ans = 0
        for i in s:
            ans = ans * 26 + ord(i) - 64
        return ans
class Solution:
    def titleToNumber(self, s: str) -> int:
        ans = 0
        for i in s:
            ans = ans * 26 + ord(i) - 64
        return ans

The runtime complexity is O(N) where N is the length of the string – given the length is 7 we can also say the complexity is O(1). The space requirement is O(1) constant.

The C++ implementation and to convert backwards from the column numbers to excel titles: Excel Sheet Column Number and Title Conversion in C++

See also: Teaching Kids Programming – Converting Spreadsheet Column Titles to Number

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
339 words
Last Post: Algorithm to Find the Kth Missing Positive Number in Array
Next Post: How to Fix CloudFlare Error 1101 (Worker threw exception)?

The Permanent URL is: Python Function to Convert Excel Sheet Column Titles to Numbers

Leave a Reply