題意:
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
思路:
其實就是個進制轉換。水水就過。倒是 Python 的代碼讓我意識到獲取字母的 ASCII 碼要用 ord 函數,不能直接強制類型轉換。
代碼:
C++:
class Solution {
public:
int titleToNumber(string s) {
int len = s.size();
int ans = 0;
for(int i = 0;i < len;++i)
ans = ans*26 + s[i] - 'A' + 1;
return ans;
}
};
Python:
class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
n = len(s)
ans = 0
for i in range(0,n):
ans = ans*26 + ord(s[i]) - ord('A') + 1
return ans