String - 168. Excel Sheet Column Title

11

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

Example 1:

Input: 1
Output: "A"

思路:

对于输入n进行取模,来确定这一位应该是什么字母,再计算剩下的数。依次类推,需要注意A是第一个,所以对n先减一再取模。

代码:

java:

class Solution {

    public String convertToTitle(int n) {

        StringBuilder sb = new StringBuilder();
        while (n > 0) {
            n--;
            sb.append((char)('A' + n % 26));
            n /= 26;
        }
        sb.reverse();
        return sb.toString();
    }
}