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

## Analysis:

This problem is pretty straightforward. Simply apply maltiplication and power of 26 (the number of chars from A-Z) will work well.

For each string, e.g. BCD:

- char D represents number D - A + 1 ===> 4
- char C represents number (26 ** 1) * (C - A + 1) ===> 78
- char B represents number (26 ** 2) * (B - A + 1) ===> 1352

## Code (C++):

class Solution {

public:

int titleToNumber(string s) {

int res = 0;

for (int i=s.size()-1;i>=0;--i){

res += (s[i]-'A' + 1) * pow(26, s.size() - i -1);

}

return res;

}

};

## Code (Python):

class Solution(object):

def titleToNumber(self, s):

"""

:type s: str

:rtype: int

"""

res = 0

for i in range(len(s)):

res += 26**(len(s)-i-1) * (ord(s[i])-ord('A') + 1)

return res

## No comments:

## Post a Comment