【EASY】Excel Sheet Column Number

发布于: 2018-12-11 13:52
阅读: 76
评论: 0
喜欢: 0

问题

原题链接:https://leetcode.com/problems/excel-sheet-column-number/

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

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

Example 1:

Input: "A"
Output: 1

Example 2:

Input: "AB"
Output: 28

Example 3:

Input: "ZY"
Output: 701

分析过程

  • 输入:Excel 的行号
  • 输出:十进制数
  • 思路:本质为进制转换,26 进制转 10 进制

解决方法

class Solution {
public:
    int titleToNumber(string s) {
        size_t len = s.size();
        int result = 0;
        for (int i = 0; i < len; i++) {
            char c = s[i];
            if (c >= 'A' && c <= 'Z') {
                result = result * 26 + (c - 'A' + 1);
            } else {
                return 0;
            }
        }
        
        return result;
    }
};

Thanks for reading.

All the best wishes for you! 💕