Categories:

Tags:



Problem

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

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

Constraints

  • 1 <= columnNumber <= 231 - 1

Solution

The problem Excel Sheet Column Title can be solved by implementing a base converter for converting a number to base 26. One thing to note is that although Z is converted into 26, it techincally should be considered as 10 as there are no characters representing 0. For example number 26 in decimal is 10 in base 26 which should be represented as A? where ? is the character for 0. However, 10 in base 26 is represented as Z instead, showing that Z needs to be considered as 10. In order to deal with this peculiarity, columnNumber needs to be subtracted by 1 every time it gets converted into a new digit.

Implementation

class Solution
{
  public:
    string convertToTitle(int columnNumber)
    {
        string ret;
        do
        {
            ret = (char)('A' + --columnNumber % 26) + ret;
            columnNumber /= 26;
        } while (columnNumber);

        return ret;
    }
};