题目 | Excel Sheet Column Title |
通过率 | 17.2% |
难度 | Easy |
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
Excel Sheet Column Title 与Excel Sheet Column Number正好是两道互逆的题目,其实就是10进制和26进制之间的转换;
思路:将每一个数字%26取得那个数字,然后把n/26取得整数,只要n>0就一直循环执行下去;需要特别注意Z的情况(即整除26);
java代码:
public class Solution { public String convertToTitle(int n) { StringBuilder sb = new StringBuilder(); if(n<0) return sb.toString(); while(n>0){ int x=n%26; if(x==0){ sb.append('Z'); n--; }else{ sb.append((char)('A'-1+x)); } n/=26; } return sb.reverse().toString(); } }