题目描述:
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;
}
};
本文介绍了一个简单的算法,用于将Excel中的列标题转换为相应的列号。例如,'A'转换为1,'Z'转换为26,而'AA'则转换为27等。通过解析每个字符并将其视为26进制数的一部分来实现这一转换。
480

被折叠的 条评论
为什么被折叠?



