题目描述:
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
题目大意:给出Excel中的列标题,返回它对应的列号。
思路:A是1, Z是26, AA是27,很容易看出这是个26进制的关系(AA = 26 + 1),逢26进1位。分离出每一位数再乘以对应权值相加即可。
c++代码:
class Solution {
public:
int titleToNumber(string s) {
int ans = 0;
int base = 1;
auto str = s.c_str();
for (int i = s.size() - 1; i >= 0; i--)
{
ans += (str[i] - 64) * base;
base *= 26;
}
return ans;
}
};