本文共 831 字,大约阅读时间需要 2 分钟。
问题描述
给定一个正整数,返回与其数值相应的Excel工作表的标题列
例如:1 -> A2 -> B3 -> C...26 -> Z27 -> AA28 -> AB
问题分析
首先了解一下在JAVA中,与字符相关的特点,请看下面的代码:
for(char i='A';i<'Z';i++) { System.out.print(i+"\t"); } System.out.println();
这段代码的输出结果为:
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
如果将字符通过类型强制转换为其对应的整数:
for(char i='A';i<='Z';i++) { System.out.print((int)i+"\t"); } System.out.println();
则,输出结果为:
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
即 字符 A 对应的整数值为 65;字符 B 对应的整数值为 66;字符 Z 对应的整数值为 90。
给出一段算法代码:
public static String convertToTitle(int n) { StringBuilder result = new StringBuilder(); while(n>0){ n--; result.insert(0, (char)('A' + n % 26)); n /= 26; } return result.toString(); }
(完)
转载地址:http://rgvdi.baihongyu.com/