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
这道题是Excel Sheet Column Number 的反算,关键就是利用mod运算算出最后一位的字母,然后需要(n-1)/26来算出下一个数字, 需要n-1是因为从27开始会变成2位数。
public String convertToTitle(int n) {
List<String> letters = Arrays.asList(" ", "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");
StringBuilder sb = new StringBuilder();
while (n!=0) {
int number = n % 26;
if (number==0) {
sb.insert(0, letters.get(26));
} else {
sb.insert(0, letters.get(number));
}
n = (n-1)/26;
}
return sb.toString();
}