题目链接:https://leetcode.com/problems/excel-sheet-column-title/
题目:
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
解题思路:
本题考点:数学的公式推导。
说白了就是找递推式。
1 -> A
1 + 26 * 1 -> AA
1 + 26 * 2 -> BA
1 + 26 * 3 -> CA
1 + 26 * (1 + 26 * 1) -> AAA
1 + 26 * (26 + 26 * 1) -> AZA
规律为:
1. 每 26 个字母为一轮,n 与 26 的每一次模值都获得一个字符的值。
2. n 与 26 的第一次模值获得从右到左第一位字符。
3. n 除以 26 更新 n。
4. 模值为 0 时,应为字母 Z。
需要注意的是,在 JAVA 中,’A’ + 1 不能直接得出字符 B,char 类型和 int 类型相加时转换为整型(向大的转),获得的是 B 的 ASCII 码,为了得到字符 B 必须进行类型转换,(char)(‘A’ + 1)。
代码实现:
public class Solution {
public String convertToTitle(int n) {
StringBuilder sb = new StringBuilder();
while(n != 0) {
int tmp = n % 26;
if(tmp == 0) {
sb.append('Z');
if(n == 26)
break;
n = (n - 26) / 26;
}
else {
sb.append((char)('A' + tmp - 1));
n /= 26;
}
}
return sb.reverse().toString();
}
}
18 / 18 test cases passed.
Status: Accepted
Runtime: 0 ms
网上更为简洁的代码实现:
参考链接:http://www.programcreek.com/2014/03/leetcode-excel-sheet-column-title-java/
public String convertToTitle(int n) {
if(n <= 0){
throw new IllegalArgumentException("Input is not valid!");
}
StringBuilder sb = new StringBuilder();
while(n > 0){
n--;
char ch = (char) (n % 26 + 'A');
n /= 26;
sb.append(ch);
}
sb.reverse();
return sb.toString();
}