Excel表格列Excel Sheet Column Title leetcode146

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

For example:ui

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

Example 1:rem

Input: 1
Output: "A"

Example 2:it

Input: 28
Output: "AB"

Example 3:static

Input: 701
Output: "ZY"

實現以下,這裏困擾個人就是和進制的區別,好比9+1變成10,而這不是26進制,AA是27,Z是26,由於沒有0的概念,因此當餘數是0的時候,要特殊處理一下。di

public static String convertToTitle(int n) {

    StringBuilder result= new StringBuilder();

    while (n > 0 ) {
        int merchant = n / 26;
        int remainder = n % 26;

        if(remainder==0) {
            result = result.append((char) ('Z'));
            merchant--;
        } else {
           result = result.append((char)('A'-1+remainder));
        }
        n = merchant;
    }
    return result.reverse().toString();

}
相關文章
相關標籤/搜索