Given a column title as appear in an Excel sheet, return its corresponding column number.
Example:
1
2
3
4
5
6
7
| A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
|
Solution
(Excel-Sheet-Column-Number.java) download
1
2
3
4
5
6
7
8
| public class Solution {
public int titleToNumber(String s) {
int ret = 0;
for (int i=0;i<s.length();i++)
ret = ret*26+(s.charAt(i)-'A'+1);
return ret;
}
}
|
(Excel-Sheet-Column-Number.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
| class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
col = dict()
for i in range(26):
col[str(unichr(65+i))] = i+1
ret = 0
for i in range(len(s)-1,-1,-1):
ret += col[s[i]]*(26 ** (len(s)-i-1))
return ret
|