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
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.
思路类似于n 进制转m 进制,取余 -> 添加 -> 移位。刚知道Java 的String 可以在前面添加的……基础有点薄弱啊。代码如下:
public class Solution {
public String convertToTitle(int n) {
String result = "";
while (n > 0) {
result = (char)(--n % 26 + 'A') + result;
n = n / 26;
}
return result;
}
}
这道题也可以用递归去解:
public class Solution {
public String convertToTitle(int n) {
return n == 0 ? "" : convertToTitle(--n / 26) + (char)('A' + (n % 26));
}
}