题目
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
我的解法
这个其实就是一个进制的转换,相当于将十进制转换为26进制,可以参考
Leetcode:Number of 1 Bits
我的代码:
public class Solution {
public String convertToTitle(int n) {
char[] A = {'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 str = "";
while (n > 26) {
int reminder = n % 26;
if (reminder == 0) {
str = A[25] + str;
n--;
}
else {
str = A[reminder - 1] + str;
}
n /= 26;
}
if (n == 26)
str = A[25] + str;
else
str = A[n - 1] + str;
return str;
}
}
缺点
保存26个单词表,浪费空间,后边因为这个数组下标对应问题,折腾好久。
参考答案:
方法一:
及其精炼!!
public class Solution {
public String convertToTitle(int n) {
return n == 0 ? "" : convertToTitle(--n / 26) + (char)('A' + (n % 26));
}
}
方法二:
public class Solution {
public String convertToTitle(int n) {
StringBuilder result = new StringBuilder();
while(n>0){
n--;
result.insert(0, (char)('A' + n % 26));
n /= 26;
}
return result.toString();
}
}
当然,上述代码中,StringBuilder可换成String,改为:
String column = "";
column = (char)('A' + n % 26) + column;
但是,StringBuilder效率比String要高,具体参考leetcode上的解释:
using simple String basically copies to a new variable, then add the new character to it. so, every time you add a character into a string, it copies the entire string, then adds the new character.【就是说,每次对String执行“+”操作,都会重新创建一个string,显然浪费内存空间】
StringBuilder doesn’t copy that string into a new variable, so it is more memory-efficient
当然有网友提到,如果不采用“头插法”拼接字符串,可以采用多次反转的办法:
1.Reverse each string you want to insert.
2.Append each string to a StringBuilder.
3.Reverse the entire StringBuilder when you’re done.