问题描述
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
思路分析
与计算excel列名相反,这道题目要求计算的是excel列的列号,相当于二十六进制转十进制。
按照定义,计算字母对应的数字,从低位开始,乘以相应的26的幂,加和为结果。
class Solution {
public:
int titleToNumber(string s) {
int result = 0, m;
int j = 0;
for(int i = s.length() - 1; i >= 0; i--){
m = s[i] - '@';
result += m*pow(26,j);
j++;
}
return result;
}
};
时间复杂度:O(n)
反思
很简单的题目。正面上:
class Solution {
public:
int titleToNumber(string s) {
int result = 0;
for(int i = 0; i < s.length(); i++){
int temp = s[i] - 'A' + 1;
result = result * 26 + temp;
}
return result;
}
};