简单实现思路:倒着走,每一位自己的序号乘以26的对应次方

  • 最末尾为C,则为 3*(26^0) = 3*1
  • 倒数第二位是D,则为 4*(26^1) = 4*26
  • 倒数第三位是B,则为 2*(26^2) = 2*676

以此类推累加即可

c++实现

class Solution {
public:
    int getNumber(string S) {
        // write code here
        int len = S.size();
        int res=0;
        for(int i=len-1; i>=0; i--){  //倒着循环,当前值*(26^(len-1-i))
            res += (S[i]-'A'+1) * pow(26, len-1-i);
        }
        return res;
    }
};

python实现一

class Solution:
    def getNumber(self , S: str) -> int:
        # write code her
        res = 0
        str_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        S = S[::-1]
        for i in range(len(S)):
            res += ((str_list.find(S[i])+1) * (26 ** i))
        return res

python实现二

class Solution:
    def getNumber(self , S: str) -> int:
        now = len(S)-1    # 初始化i
        res = 0
        str_list = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        while now>=0:
            res += ((str_list.find(S[now]) + 1) * (26 ** (len(S)-1-now)))
            now -= 1
        return res