leetcode171 Excel Sheet Column Number-zh
# 171. Excel表列序号 (opens new window)
English Version (opens new window)
# 题目描述
给定一个Excel表格中的列名称,返回其相应的列序号。
例如,
A -> 1 B -> 2 C -> 3 ... Z -> 26 AA -> 27 AB -> 28 ...
示例 1:
输入: "A" 输出: 1
示例 2:
输入: "AB" 输出: 28
示例 3:
输入: "ZY" 输出: 701
致谢:
特别感谢 @ts 添加此问题并创建所有测试用例。
# 解法
# Python3
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
res = 0
for c in columnTitle:
res = res * 26 + (ord(c) - ord('A') + 1)
return res
1
2
3
4
5
6
2
3
4
5
6
# Java
class Solution {
public int titleToNumber(String columnTitle) {
int res = 0;
for (char c : columnTitle.toCharArray()) {
res = res * 26 + (c - 'A' + 1);
}
return res;
}
}
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
# TypeScript
function titleToNumber(columnTitle: string): number {
let res: number = 0;
for (let char of columnTitle) {
res = res * 26 + char.charCodeAt(0) - 64;
}
return res;
};
1
2
3
4
5
6
7
2
3
4
5
6
7
# C++
class Solution {
public:
int titleToNumber(string columnTitle) {
int res = 0;
for (char c : columnTitle) {
res = res * 26 + (c - 'A' + 1);
}
return res;
}
};
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# ...
1
编辑 (opens new window)
上次更新: 2021/10/30, 12:58:38