给你一个整数 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"
package com.example.lettcode.math;
/**
* @Class ConvertToTitle
* @Description 166 Excel表列名称
* @Author
* @Date 2021/6/29
**/
public class ConvertToTitle {
public static String convertToTitle(int columnNumber) {
if (columnNumber <= 0 || columnNumber > Integer.MAX_VALUE) return "";
StringBuilder titleStr = new StringBuilder("");
while (columnNumber != 0) {
int tmp = columnNumber % 26;
if (tmp == 0) {
// 减1操作是为了把进制转换的0-25变成1-26
columnNumber--;
tmp = 26;
}
titleStr.append((char) ('A' + tmp - 1));
columnNumber /= 26;
}
return titleStr.reverse().toString();
}
}
// 测试用例
public static void main(String[] args) {
int columnNumber = 1;
String titleStr = ConvertToTitle.convertToTitle(columnNumber);
System.out.println("ConvertToTitle demo01 result : " + titleStr);
columnNumber = 26;
titleStr = ConvertToTitle.convertToTitle(columnNumber);
System.out.println("ConvertToTitle demo02 result : " + titleStr);
columnNumber = 52;
titleStr = ConvertToTitle.convertToTitle(columnNumber);
System.out.println("ConvertToTitle demo03 result : " + titleStr);
columnNumber = 28;
titleStr = ConvertToTitle.convertToTitle(columnNumber);
System.out.println("ConvertToTitle demo04 result : " + titleStr);
columnNumber = 701;
titleStr = ConvertToTitle.convertToTitle(columnNumber);
System.out.println("ConvertToTitle demo05 result : " + titleStr);
}