168.Excel Sheet Column Title === ###### tags: `Easy` `String` `Math` [168. Excel Sheet Column Title](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 > ... ### 範例 **Example 1:** ``` Input: columnNumber = 1 Output: "A" ``` **Example 2:** ``` Input: columnNumber = 28 Output: "AB" ``` **Example 3:** ``` Input: columnNumber = 701 Output: "ZY" ``` **Constraints**: * 1 <= `columnNumber` <= 2^31^ - 1 ### 解答 #### TypeScript ```typescript function convertToTitle(columnNumber: number): string { const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; let result = ''; while (columnNumber > 0) { columnNumber--; // 1-based to 0-based const rem = columnNumber % 26; result = letters[rem] + result; columnNumber = ~~(columnNumber / 26); } return result; } ``` > [name=sheep][time=Tues, 22 Aug 2023] #### javascript ```javascript= function convertToTitle(columnNumber) { const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; const title = []; while (columnNumber > 26) { columnNumber--; const remainder = columnNumber % 26; columnNumber = Math.floor(columnNumber / 26); title.push(alphabet[remainder]); } title.push(alphabet[columnNumber - 1]); return title.reverse().join(''); } ``` > 貼完看到上面的,被我弟虐爆,完全不知道我在寫三小。 > [name=Marsgoat][time=Tues, 22 Aug 2023] ### Reference [回到題目列表](https://marsgoat.github.io/XNnote/coding/leetcodeEveryDay.html)