题目要求:
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
简单点说:这一题目相当于是 10进制转换 26进制
注意点:在临界的条件到来时对代码的处理
public class solution {
public String convertToTitle(int n) {
//该题目的解决方法相当于数26进制数据的转换
//首先创建 HashMap进行数据的保存
Map<Integer, Character> map = new HashMap<>();
StringBuffer sb = new StringBuffer();
for(int i = 1; i < 27; i++) {
map.put(i, (char)('A' + i - 1));
}
while(n > 0) {
int temp = n % 26;
if(n % 26 == 0) temp = 26;
sb.insert(0,map.get(temp));
n /= 26;
if(temp == 26) n--;
}
return sb.toString();
}
}
update
其实不用map也是可以成功处理的
public class solution {
public String convertToTitle(int n) {
StringBuffer sb = new StringBuffer();
while(n > 0) {
int temp = n % 26;
if(n % 26 == 0) temp = 26;
sb.insert(0,(char)('A' + temp - 1));
n /= 26;
if(temp == 26) n--;
}
return sb.toString();
}
}