【LeetCode】Excel Sheet Column Number

     題意:

Related to question Excel Sheet Column Title

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 

     

     思路:

     其實就是個進制轉換。水水就過。倒是 Python 的代碼讓我意識到獲取字母的 ASCII 碼要用 ord 函數,不能直接強制類型轉換。


     代碼:

     C++:

class Solution {
public:
    int titleToNumber(string s) {
        int len = s.size();
        int ans = 0;
        for(int i = 0;i < len;++i)
            ans = ans*26 + s[i] - 'A' + 1;
        return ans;
    }
};

     Python:

class Solution:
    # @param s, a string
    # @return an integer
    def titleToNumber(self, s):
        n = len(s)
        ans = 0
        for i in range(0,n):
            ans = ans*26 + ord(s[i]) - ord('A') + 1
        return ans

發佈了123 篇原創文章 · 獲贊 268 · 訪問量 111萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章