題目
給定一個Excel表格中的列名稱瑞信,返回其相應的列序號酪夷。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
輸入: "A"
輸出: 1
示例 2:
輸入: "AB"
輸出: 28
示例 3:
輸入: "ZY"
輸出: 701
致謝:
特別感謝 @ts 添加此問題并創(chuàng)建所有測試用例网严。
C++解法
這是第168題的逆向題祠挫,現(xiàn)在和168題一起給出答案那槽。
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
string convertToTitle(int n) {
string result;
do {
--n;
result.push_back('A' + n % 26);
} while (n /= 26);
reverse(result.begin(), result.end());
return result;
}
int titleToNumber(string s) {
int result = 0;
for (auto c: s) {
result = 26 * result + c - 'A' + 1;
}
return result;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
Solution solution;
for (int i = 1; i < 100; i++) {
auto str = solution.convertToTitle(i);
cout << str << endl;
cout << solution.titleToNumber(str) << endl;
}
return 0;
}
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/excel-sheet-column-number