LeetCode #171 Excel Sheet Column Number Excel表列序號

171 Excel Sheet Column Number Excel表列序號

Description:
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:

Example 1:
Input: "A"
Output: 1

Example 2:
Input: "AB"
Output: 28

Example 3:
Input: "ZY"
Output: 701

題目描述:
給定一個Excel表格中的列名稱,返回其相應(yīng)的列序號。

例如,

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

示例:

示例 1:
輸入: "A"
輸出: 1

示例 2:
輸入: "AB"
輸出: 28

示例 3:
輸入: "ZY"
輸出: 701

思路:

相當(dāng)于 26進制轉(zhuǎn)化為 10進制
時間復(fù)雜度O(n), 空間復(fù)雜度O(1)

代碼:
C++:

class Solution 
{
public:
    int titleToNumber(string s) 
    {
        int result = 0;
        for (auto c : s) 
        {
            result *= 26;
            result += c - 'A' + 1;
        }
        return result;
    }
};

Java:

class Solution 
{
    public int titleToNumber(String s) 
    {
        int result = 0;
        for (char c : s.toCharArray()) {
            result *= 26;
            result += c - 'A' + 1;
        }
        return result;
    }
}

Python:

class Solution:
    def titleToNumber(self, s: str) -> int:
        result = 0
        for i in s:
            result *= 26
            result += ord(i) - ord('A') + 1
        return result
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容