181.Excel Sheet Column Title

题目:

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

给定正整数,返回Excel工作表中显示的相应列标题。

For example:

    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB 
    ...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

解答:

方法一:

 1 class Solution {
 2     public String convertToTitle(int n) {
 3         String res="";
 4         while(n>0){
 5             res=(char)((--n)%26+'A')+res;  //注意不能写成res+=,不然会逆序,还要进行反转操作
 6             n/=26;
 7         }
 8         return res;
 9     }
10 }

方法二:递归

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

详解:

 

posted @ 2018-09-20 15:35  chan_ai_chao  阅读(118)  评论(0编辑  收藏  举报