一.解法
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ì)算,具體公式為的遍歷總合,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;
}
}