问题描述:
Related to question Excel Sheet Column Title
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
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
本题类似于进制转换,将一个字符串转化为一个十进制的数字,而要求的字符串可以看作是一个26进制的数字。具体解法如下:
C++:
class Solution {
public:
int titleToNumber(string s) {
if(s.empty())
return 0;
int n = 0;
for(int i = 0; i < s.length()-1; i ++){
n = (int(s[i]-'A')+1+n) * 26;
}
n += int(s[s.length()-1]-'A')+1;
return n;
}
};
python:
class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
if len(s) == 0:
return 0
n = 0
for i in range(0,len(s)-1):
n = (ord(s[i]) - ord('A') + 1 + n)*26
n = n + ord(s[len(s)-1]) - ord('A') + 1
return n
这里需要用到python字符转换为数字的函数:ord