LeetCode Notes: Excel Sheet Column Title

Question

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 
...

Example 1:

Input: columnNumber = 1

Output: "A"

Example 2:

Input: columnNumber = 28

Output: "AB"

Example 3:

Input: columnNumber = 701

Output: "ZY"

Example 4:

Input: columnNumber = 2147483647

Output: "FXSHRXW"

Constraints:

  • 1 <= columnNumber <= 231 - 1

For questions of the same type, please refer to

LeetCode Notes: Excel Sheet Column Number

Solution

Analysis:

The decimal system is converted to the 26 system. The core algorithm is to divide 26 continuously, and find the letter corresponding to the remainder from right to left.

Code:

/**
  * @param {number} columnNumber
  * @return {string}
  */
var convertToTitle = function(columnNumber) {

     // Store the result
     const arr = []
     //Until columnNumber is less than 26, it is the last loop
     while(columnNumber){
         //If it is 27, after subtracting 1, 26 % 26 is equal to 0, and fromCharCode(0+65) gets the next A
         columnNumber--
         const remainder = columnNumber% 26
         arr.unshift(String.fromCharCode(remainder + 65))
         // Get a multiple of 26 to proceed, the next cycle
         columnNumber = parseInt(columnNumber / 26)
     }

     return arr.join('')
};

Reference

Comments