Appearance
168. Excel 表列名称
给你一个整数 columnNumber ,返回它在 Excel 表中相对应的列名称。
例如:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
输入:columnNumber = 1
输出:"A"
示例 2:
输入:columnNumber = 28
输出:"AB"
示例 3:
输入:columnNumber = 701
输出:"ZY"
示例 4:
输入:columnNumber = 2147483647
输出:"FXSHRXW"
提示:
1 <= columnNumber <= 231 - 1
- 来源:力扣(LeetCode)
- 链接:https://leetcode.cn/problems/excel-sheet-column-title
javascript
/**
* @param {number} columnNumber
* @return {string}
*/
var convertToTitle = function (columnNumber) {
var words = [
"",
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
],
res = ""
var left = columnNumber
while (left) {
if (left > 0 && left <= 26) {
res = words[left] + res
left = 0
} else {
rest = left % 26
res = rest === 0 ? words[26] + res : words[rest] + res
left =
rest === 0
? Math.floor((left - rest) / 26) - 1
: Math.floor((left - rest) / 26)
}
}
return res
}
console.log(convertToTitle(1) === "A")
console.log(convertToTitle(26) === "Z")
console.log(convertToTitle(28) === "AB")
console.log(convertToTitle(52) === "AZ")
console.log(convertToTitle(701) === "ZY")
console.log(convertToTitle(24568) === "AJHX")
console.log(convertToTitle(2147483647) === "FXSHRXW")