跳转至

168. Excel Sheet Column Title

Leetcode Math

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 
    ...

Example 1:

Input: 1
Output: "A"

Example 2:

Input: 28
Output: "AB"

Example 3:

Input: 701
Output: "ZY"

分析

从最后一位开始“解码”,比较容易计算。特别需要注意是26的倍数,这种情况:最后一个字母为Z。

public String convertToTitle(int n) {
    StringBuilder sb = new StringBuilder(); 
    while (n != 0){
        if (n % 26 == 0){
            sb.append('Z');
            n -= 26; }
        else sb.append((char)('A' + n % 26 - 1));
        n /= 26;
    }
    return sb.reverse().toString();
}