題目
難度級別:簡單
給定一個Excel表格中的列名稱,返回其相應的列序號。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
輸入: "A"
輸出: 1
示例 2:
輸入: "AB"
輸出: 28
示例 3:
輸入: "ZY"
輸出: 701
解題思路
法一
通過進制轉換可得
const titleToNumber = function(s) {
let str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
let res = 0
for(let i = 0; i < s.length; i++)
for(let j = 0; j < str.length; j++)
if(s[i] === str[j])
res += (j + 1) * 26**(s.length - 1 - i)
return res;
};
charCodeAt
將字符轉化爲ASCII碼,A-Z是連續的,且A爲65,所以轉換以後減一個65 + 1,值就在1-26裏了。
const titleToNumber = function(s) {
let res = 0
for(let i = 0; i < s.length; i++)
res += (s[i].charCodeAt()-65 +1) * 26**(s.length-1-i)
return res;
};
題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/excel-sheet-column-number