LeetCode-Excel Sheet Column Title

女爷i 2022-08-09 10:59 61阅读 0赞

Problem:
Given a positive integer, return its corresponding column title as appear in an Excel sheet.

For example:

  1. 1 -> A
  2. 2 -> B
  3. 3 -> C
  4. ...
  5. 26 -> Z
  6. 27 -> AA
  7. 28 -> AB

Analysis:
要求是用字母表示数字,1-26用A-Z表示,超过26的用A-Z分别代表进位的26个权值,实质上该题是10进制转26进制但是A等价于0
Anwser:
找了一位大牛的代码,从这段代码中可以学到更多的有关进制转换的问题。
该代码巧妙的利用了递归的方法:

  1. public class Solution {
  2. public String convertToTitle(int n) {
  3. return n<=0?"":convertToTitle((n-1)/26)+(char)('A'+(n-1)%26);
  4. }
  5. }

其实上段代码也可以写成一般的形式,而非一行代码,如:

  1. public class Solution {
  2. public String convertToTitle(int n) {
  3. if(n<=0) return "";
  4. else {
  5. int num = (n-1) / 26;
  6. int res = (n-1) % 26;
  7. return convertToTitle(num)+(char)(res+'A');
  8. }
  9. }
  10. }

发表评论

表情:
评论列表 (有 0 条评论,61人围观)

还没有评论,来说两句吧...

相关阅读