171. Excel Sheet Column Number

1. Description

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

2. Example

Example 1:
Input: “A”
Output: 1

Example 2:
Input: “AB”
Output: 28

Example 3:
Input: “ZY”
Output: 701

3. Constraints

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

4. Solutions

My Accepted Solution

n = i_str.size()
Time complexity: O(n)
Space complexity: O(1)

class Solution 
{
public:
    // int titleToNumber(string s)
    int titleToNumber(string &i_str) 
    {
        int result = 0;
        for(long i = i_str.size() - 1, base = 1; i >= 0; i--, base *= 26)
        {
            result += (i_str[i] - 'A' + 1) * base;
        }
            
        return result;
    }
};
Last updated:
Tags: Math
comments powered by Disqus