Total Accepted: 9173
Total Submissions: 52899
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB
这是第一次想出来的方案
只是马上就想出来 就写了。结果发现有很多不严谨的地方,然后又仔细考虑了一下这个题
public static String convertToTitle(int n) {
char[] Map = { ' ', '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' };
String result = "";
while (n >= 26) {
result += 'Z';
n -= 26;
}
if (n > 0) {
result += Map[n];
}
return result;
}
分析思路:
这道题和转进制有一点不同,因为他没有0,而且是27进制的没有0的一个计数法则。
比如26是Z。27就是AA。
所以尾数的是n%27为下标的Map值。
倒数第二位是有几个26为下标但是有一个就不算,比如27是有一个26加一个1,就是AA。
但是如果是52呢,就是有两个26,但正确答案应该是AZ,所以我的处理办法是先让n-1再除
最后成功Accepted
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
System.out.println(convertToTitle(26));
System.out.println(convertToTitle(27));
System.out.println(convertToTitle(52));
System.out.println(convertToTitle(701));
System.out.println(convertToTitle(703));
}
public static String convertToTitle(int n) {
char[] Map = { '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', 'Z' };
int tail = n % 26;
String result = "" + Map[tail];
int num = (n - 1) / 26;
while (num > 0) {
result = Map[num % 26] + result;
num =(num-1)/ 26;
}
return result;
}
}