题目链接:https://leetcode.com/problems/excel-sheet-column-number/
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
思路:很简单的一个26进制转换成10进制,有一个陷阱是没有说明大小写是等价的。
代码如下:
class Solution {
public:
int titleToNumber(string s) {
int sum = 0;
for(int i = 0; i< s.size(); i++)
sum = sum*26 + toupper(s[i]) - 'A' + 1;
return sum;
}
};
python
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
ans = 0
for index in range(len(s)):
ans = ans*26 + ord(s[index]) - ord('A') + 1
return ans;