题目链接:点击打开链接
题目:
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
思路:
类似十进制转化为二十六进制,要注意如果n可以被26除尽,最后一位没有0表示最小只有A,这里用Z表示。
所以要考虑两种情况,如果可以被26除尽,最后一位固定为Z,(n-26)/26考虑前面位数的转化;如果不能被除尽,直接考虑所有位数的转化。
算法:
-
public String convert(int n) {
-
String result = "";
-
while (n % 26 != 0) {
-
result = (char) (n % 26 + 64) + result;
-
n = n / 26;
-
}
-
if (n / 26 != 0) {
-
result = (char) (n + 64) + result;
-
}
-
return result;
-
}
-
-
public String convertToTitle(int n) {
-
String result = "";
-
if (n <= 26) {
-
return String.valueOf((char) (n + 64));
-
}
-
if (n % 26 == 0) {
-
result = convert((n-26)/26) + ‘Z‘;
-
return result;
-
} else {
-
result = convert(n);
-
}
-
return result;
-
}
【Leetcode】Excel Sheet Column Title
原文:http://blog.csdn.net/yeqiuzs/article/details/51615480