Excel 列标题转数字:A=1, B=2, ..., Z=26, AA=27, AB=28, ...
字符 'A'~'Z' 对应数字 1~26。从左到右累加:ans = ans * 26 + (c - 'A' + 1)。
class Solution {
public:
int titleToNumber(string s) {
int ans = 0;
for (char c : s)
ans = ans * 26 + (c - 'A' + 1);
return ans;
}
};
class Solution:
def titleToNumber(self, s: str) -> int:
ans = 0
for c in s:
ans = ans * 26 + ord(c) - ord('A') + 1
return ans
string convertToTitle(int n) {
string s;
while (n) {
--n; // 关键:1-based 调整
s.push_back('A' + n % 26);
n /= 26;
}
reverse(s.begin(), s.end());
return s;
}