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 -> ABSolution 1 0ms 7.23%
public class Solution {
public String convertToTitle(int n) {
if (n <= 0) {
return "";
}
StringBuilder res = new StringBuilder();
while (n > 0) {
if (n % 26 == 0) {
res.append('Z');
n = n / 26 - 1;
} else {
char crt = (char)('A' + n % 26 - 1);
res.append(crt);
n = n / 26;
}
}
return res.reverse().toString();
}
}
Solution 2
0ms 7.23
public class Solution {
public String convertToTitle(int n) {
if (n == 0) {
return "";
}
return convertToTitle((n - 1) / 26) + (char)((n - 1) % 26 + 'A');
}
}