LeetCode簡(jiǎn)單題:171. Excel表列序號(hào)(Python,C++,Java)

一.解法

https://leetcode-cn.com/problems/excel-sheet-column-number/
要點(diǎn):進(jìn)制轉(zhuǎn)換
這題比168. Excel表列名稱簡(jiǎn)單因?yàn)槭钦虻牟挥每紤]168題的錯(cuò)位減一,直接利用公式循環(huán)計(jì)算即可,也可以哈希表把A-Z映射到1-26再計(jì)算,具體公式為當(dāng)前字母*pow(26,length-1-i)的遍歷總合,length表示string長(zhǎng)度,i從0開(kāi)始表示第幾位(從左到右)。
Python,C++,Java都用了相同的進(jìn)制轉(zhuǎn)換法。

二.Python實(shí)現(xiàn)

class Solution:
    def titleToNumber(self, s: str) -> int:
        l = len(s)
        value = 0
        hashmap = {}
        for i in range(1, 27):
            hashmap[chr(i+64)] = i
        i=0
        for ch in s:  
            value +=  hashmap[ch] * 26**(l-1-i)
            i+=1
                
        return value

三.C++實(shí)現(xiàn)

class Solution {
public:
    int titleToNumber(string s) {
        int answer=0;
        int length=s.size();
        for(int i=0;i<length;i++){
            answer+=(s[i]-64)*pow(26,length-i-1);
        }
        return answer;

    }
};

四.java實(shí)現(xiàn)

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

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