Excel Sheet Column Title

 

 

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 

The key is n--. The minimum in 26-bit number is mapped to 1, not 0.

 

public class Solution {
    public String convertToTitle(int n) {
        if(n<=0)return "";
        
        
        StringBuilder sb = new StringBuilder();
        while(n>0)
        {
            n--;
            char c = (char)(n%26+'A');
            sb.append(c);
            n = n/26;
        }
        sb.reverse();
        
        return sb.toString();
    }
}

reference: http://www.programcreek.com/2014/03/leetcode-excel-sheet-column-title-java/

 

 

另一种解法:

public class Solution {
    public String convertToTitle(int n) {
        StringBuilder result = new StringBuilder();

        while(n>0){
            n--;
            result.insert(0, (char)('A' + n % 26));
            n /= 26;
        }

        return result.toString();
    }
}

reference: https://leetcode.com/discuss/19150/accepted-java-solution

posted @ 2016-05-09 07:01  Hygeia  阅读(167)  评论(0编辑  收藏  举报