给定一个正整数,返回它在 Excel 表中相对应的列名称。
例如,
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB ... 示例 1:
输入: 1 输出: “A” 示例 2:
输入: 28 输出: “AB” 示例 3:
输入: 701 输出: “ZY”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/excel-sheet-column-title
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
个人理解使用26进制计算
class Solution {
public String convertToTitle(int n) {
String[] str={"Z","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"};
StringBuilder sb = new StringBuilder();
while(n>0){
int tem=n%26;
sb.insert(0,str[tem]);
if(tem==0){
n=(n-26)/26;
}else{
n/=26;
}
}
return sb.reverse().toString();
}
}
使用ascii码
class Solution {
public String convertToTitle(int n) {
StringBuilder sb = new StringBuilder();
//使用ascii码 'A':65
while(n>0){
int tem=n%26;
if(tem==0){
n=(n-26)/26;
tem=26;
}else{
n/=26;
}
sb.insert(0,(char)('A'+tem-1));
}
return sb.toString();
}
}