[LeetCode] 168. Excel Sheet Column Title

Problem

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

For example:

1
2
3
4
5
6
7
8
    1 -> A
    2 -> B
    3 -> C
    ...
    26 -> Z
    27 -> AA
    28 -> AB
    ...

Example 1:

1
2
Input: 1
Output: "A"

Example 2:

1
2
Input: 28
Output: "AB"

Example 3:

1
2
Input: 701
Output: "ZY"

Explanation

  1. We know 1 to 26 is A-Z, 27 is AA, so we need to use module 26 to get the remainder. If n is 28, answer should be AB. We know 28 % 26 = 2, then we get 'A'+2-1 = 'B'. We get one of the result character, then we divide 26, we get 28 / 26 = 1, which is 'A'+1-1='A'.

  2. At the end, we reverse the string from 'BA' to 'AB'. Note: Special case is if n is 26, 26 % 26 = 0, 'A'+0-1 doesn’t give us any letter. To solve this, we can --n first, then get the result character by --n%26+'A', which is Z.

Solution

1
2
3
4
5
6
7
8
9
10
11
class Solution {
    public String convertToTitle(int n) {
        StringBuilder sb = new StringBuilder();
        while (n > 0) {
            sb.append((char) (--n % 26 + 'A'));
            n = n / 26;
        }

        return sb.reverse().toString();
    }
}