给你一个整数 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"
方法:
数学
5017 = 7*26^2 + 10*26^1 + 25*26^0
(1)5017%26 -> 25 -> "Y"
(2)(5017-25)/26 = 192
192%26 -> 10 -> "J"
(3)(192-10)/26 = 7
7%26 -> 7 -> "G"
==> "GJY"
代码:
// 168. Excel表列名称
static void test_168() {
//int num = 1;
//int num = 28;
//int num = 701;
//int num = 5017;
int num = 2147483647;
String ret = convertToTitle(num);
System.out.println("ret:" + ret);
}
static String convertToTitle(int columnNumber) {
int[] keys = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26};
String[] values = {"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", "Z"};
Map<Integer, String> map = new HashMap<>();
String ans = "";
for (int i = 0; i < keys.length; i++) {
map.put(keys[i], values[i]);
}
int remainder = 0;
while (columnNumber != 0) {
remainder = columnNumber%26;
//System.out.println("remainder:" + remainder);
if (remainder == 0) {
remainder = 26;
}
ans += map.get(remainder);
columnNumber = (columnNumber - remainder)/26;
//System.out.println("columnNumber:" + columnNumber);
}
// 字符串反转
return new StringBuffer(ans).reverse().toString();
}