168. Excel Sheet Column Title

Leetcode

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

題目

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

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

解答

  • 方法一

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

var convertToTitle = function(columnNumber) {
    const getChar = (val) => String.fromCharCode(val + 64);
    
    let res = "";
    while(columnNumber > 26) {
        const rest = columnNumber % 26;
        res += getChar(rest || 26);
        columnNumber = Math.floor((rest ? columnNumber : columnNumber - 1) / 26);
    }
    res += getChar(columnNumber);
    
    return res.split('').reverse().join('');
};

Runtime: 72 ms, faster than 63.66% of JavaScript online submissions for Excel Sheet Column Title.

Memory Usage: 38.8 MB, less than 16.12% of JavaScript online submissions for Excel Sheet Column Title.

測資

let columnNumber = 27; // AA
columnNumber = 52; // AZ
columnNumber = 2147483647; // FXSHRXW

console.log(convertToTitle(columnNumber));

Last updated

Was this helpful?