Leetcode:Excel Sheet Column Number

Excel表格的列數

好久沒做leetcode,好久也沒寫博客。增加了許多很好的變化,Leetcode增加了Accepted Solutions Runtime Distribution,能夠看到自己的代碼的效率和別人比起來在怎麼樣的位子。CSDN博客終於推出了Markdown格式寫博客。

題目: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

class Solution {
public:
    int titleToNumber(string s) {
        //本質上是進制轉換
        int col = 0, n = s.size();
        if (n == 0)
            return 0;
        for(int i=0;i<n;i++)
        {
            if(s[i]<'A' || s[i]>'Z')
                return 0;
            col = col*26 + (s[i]-'A'+1);
        }
        return col;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章