171. Excel Sheet Column Number

Leetcode

https://leetcode.com/problems/excel-sheet-column-number/

題目

Given a string columnTitle that represents the column title as appear in an Excel sheet, return its corresponding column number.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28 
...

解答

  • 方法一

// 'A'.charCodeAt(0) === 65;

var titleToNumber = function(columnTitle) {
    let res = 0;
    for(let i=0; i<columnTitle.length; i++) {
        const factor = columnTitle.length - 1 - i;
        res += (columnTitle.charCodeAt(i) - 64) * (factor ? 26 ** factor : 1);
    }
    return res;
};

Runtime: 88 ms, faster than 74.43% of JavaScript online submissions for Excel Sheet Column Number.

Memory Usage: 40.4 MB, less than 31.92% of JavaScript online submissions for Excel Sheet Column Number.

測資

let columnTitle = 'AB'; // 27
columnTitle = 'AZ'; // 52
columnTitle = "ZY"; // 701
columnTitle = "FXSHRXW"; // 2147483647

console.log(titleToNumber(columnTitle))

Last updated

Was this helpful?