leetcode168 Excel Sheet Column Title-zh
# 168. Excel 表列名称 (opens new window)
English Version (opens new window)
# 题目描述
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ...
示例 1:
输入: 1 输出: "A"
示例 2:
输入: 28 输出: "AB"
示例 3:
输入: 701 输出: "ZY"
# 解法
# Python3
class Solution:
def convertToTitle(self, columnNumber: int) -> str:
res = []
while columnNumber:
columnNumber -= 1
res.append(chr(ord('A') + columnNumber % 26))
columnNumber //= 26
return ''.join(res[::-1])
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# Java
class Solution {
public String convertToTitle(int columnNumber) {
StringBuilder res = new StringBuilder();
while (columnNumber != 0) {
--columnNumber;
res.append((char) ('A' + columnNumber % 26));
columnNumber /= 26;
}
return res.reverse().toString();
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# TypeScript
function convertToTitle(columnNumber: number): string {
let res: string[] = [];
while (columnNumber > 0) {
--columnNumber;
let num: number = columnNumber % 26;
res.unshift(String.fromCharCode(num + 65));
columnNumber = Math.floor(columnNumber / 26);
}
return res.join('');
};
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# C#
public class Solution {
public string ConvertToTitle(int columnNumber) {
StringBuilder res = new StringBuilder();
while (columnNumber != 0) {
--columnNumber;
res.Append((char) ('A' + columnNumber % 26));
columnNumber /= 26;
}
return new string(res.ToString().Reverse().ToArray());
}
}
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38