Leetcode171. Excel表列序号

题目

给定一个Excel表格中的列名称,返回其相应的列序号。

例如,

    A -> 1
    B -> 2
    C -> 3
    ...
    Z -> 26
    AA -> 27
    AB -> 28 
    ...

示例 1:

输入: "A"
输出: 1

示例 2:

输入: "AB"
输出: 28

示例 3:

输入: "ZY"
输出: 701
致谢:
特别感谢 @ts 添加此问题并创建所有测试用例。

C++解法

这是第168题的逆向题,现在和168题一起给出答案。

#include 
#include 
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

你可能感兴趣的:(Leetcode171. Excel表列序号)