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
  • Brain storm:

    • I first opened excel to try and simulate the pattern for myself. I first noticed that num % 26 always returns the least significant letter. Then it hit me, this is just base 26, with [1-26] represented through [A-Z]. So all I had to do was convert the given number into base 26 using this format.

  • Base conversion algorithm works as follows:

    • The most significant 'digit' is the number of time the max power can fit into the original number. We mod by 26 because we want to get the mapping letter.

    • The next significant 'digit' is the same thing with the max power shifted down by 1.

map<int, char> mapAlpha() {
    string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    int count = 1;
    map<int, char> alphaInteger;

    for (auto c : alphabet) {
        alphaInteger[count % 26] = c;
        count++;
    }

    return alphaInteger;
}

int findMaxPower(int n) {
    int max = 0;
    int count = 0;
    while (n > max) {
        max = pow(26, count++);
    }
    count = count - 2;
    return count > 0 ? count : 0;
}

string convertToTitle(int n, map<int, char> &alphaMap) {
    string s = "";

    if (n == 0) 
        return s = "invalid";

    int max = findMaxPower(n);

    while (max >= 0) {
        int key = int(floor(n / pow(26, max--))) % 26;
        s += alphaMap.find(key)->second;
    }

    return s;
}

int main()
{
    map<int, char> alphaMap = mapAlpha();
    cout << convertToTitle(52, alphaMap) << endl;

    for (int i = 0; i < 1000; i++) {
        cout << convertToTitle(i, alphaMap) << " ";
    }
}

Last updated