171. Excel Sheet Column Number
給定一個字符串 columnTitle,它表示 Excel 表中的列標題,返回其對應的列號。
例如:A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
範例 1:
輸入:columnTitle = "A"
輸出:1
Python
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
result = 0
for char in columnTitle:
result = result * 26 + (ord(char) - ord('A') + 1)
return result
C++
class Solution {
public:
int titleToNumber(string columnTitle) {
int result = 0;
for (char c : columnTitle) {
result = result * 26 + (c - 'A' + 1);
}
return result;
}
};
7.74MB, 2ms
Javascript
/**
* @param {string} columnTitle
* @return {number}
*/
var titleToNumber = function(columnTitle) {
let result = 0;
for (let i = 0; i < columnTitle.length; i++) {
result = result * 26 + (columnTitle.charCodeAt(i) - 'A'.charCodeAt(0) + 1);
}
return result;
};
52.32MB, 70ms