Problem
Related to question Excel Sheet Column Title
Given a column title as appear in an Excel sheet, return its corresponding column number.
Example
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
Algorithm
26进制
整理一下题意:给定Excel表格中的一个string列号,要求返回其对应的int列号。
数学中的进制转换问题,小心处理特殊情况即可。由样例可知,需要将26进制转换为10进制。
代码如下。
//版本,时间复杂度O(n)
class Solution {
public:
int titleToNumber(string s) {
int col=0;
for(int i=0;i<s.size();i++){
col+=(s[i]-'A'+1)*pow(26,s.size()-i-1);
}
return col;
}
};