Excel表列名称 excel sheet column title
题目
给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
...
```
示例 1:
输入: 1
输出: “A”
示例 2:
输入: 28
输出: “AB”
示例 3:
输入: 701
输出: “ZY”
代码模板:
class Solution {
public String convertToTitle(int n) {
}
}
# 分析
这道题就是一个余数的概念。1-26分别代表A-Z,其实这道题也和二进制,或者十进制的计算类似,但不一样。这里不能直接把n/26,而是需要(n-1)/26,是这样的,余数只有0-25,因为26*26+26表示为ZZ,可以理解为(25+1) *26+(25+1),所以每次都需要-1再/26。
# 解答
class Solution {
public String convertToTitle(int n) {
StringBuffer result = new StringBuffer();
while(n>0){
int remainder = (n-1) % 26;
result.append(getChar(remainder));
n = (n-1)/26;
}
return result.reverse().toString();
}
public char getChar(int n){
char res = (char)(n+65);
return res;
}
}