Description
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
...
Solution
其实就是转换进制的思路。值得注意的地方是需要n - 1,使得0 -> A,25 -> Z。
Iterative
class Solution {
public String convertToTitle(int n) {
if (n < 1) {
return null;
}
StringBuilder title = new StringBuilder();
while (n > 0) {
char c = (char) ((n - 1) % 26 + 'A');
title.insert(0, c);
n = (n - 1) / 26;
}
return title.toString();
}
}
Recursive
递归的做法简介,但由于string相加的时间复杂度是O(k),此解法的时间复杂度是?!
class Solution {
public String convertToTitle(int n) {
if (n < 1) {
return "";
}
return convertToTitle(--n / 26) + (char) (n % 26 + 'A');
}
}