LeetCode-Excel Sheet Column Title
Problem:
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
Analysis:
要求是用字母表示数字,1-26用A-Z表示,超过26的用A-Z分别代表进位的26个权值,实质上该题是10进制转26进制但是A等价于0
Anwser:
找了一位大牛的代码,从这段代码中可以学到更多的有关进制转换的问题。
该代码巧妙的利用了递归的方法:
public class Solution {
public String convertToTitle(int n) {
return n<=0?"":convertToTitle((n-1)/26)+(char)('A'+(n-1)%26);
}
}
其实上段代码也可以写成一般的形式,而非一行代码,如:
public class Solution {
public String convertToTitle(int n) {
if(n<=0) return "";
else {
int num = (n-1) / 26;
int res = (n-1) % 26;
return convertToTitle(num)+(char)(res+'A');
}
}
}
还没有评论,来说两句吧...