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

```cpp
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) << " ";
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/168_excel_sheet_column_title.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
