Tuesday, August 22nd

 Excel Column Names

Given an integer, convert it to the corresponding column name in Excel

Image courtesy of Johannes Jansson via Wikipedia, licensed under the Creative Commons Attribution 2.5 Denmark license.  No changes made.

The solution is to basically convert the integer value to a base 26 value as text.  The only hiccup is that the Excel columns are indexed at 1, not 0.  Meaning the first column A corresponds to 1, not 0.

This can be fixed by decrementing the value before converting it to text

Otherwise it's straight forward.  Take the modulo of the input, at the integer value of 'A' to the number, then add it to the result.  Finally, divide the number by 26.  Continue until the input is 0.

    string res;
    while (columnNumber) {
            columnNumber--;
            char c = 'A' + columnNumber % 26;
            res = c + res;
            columnNumber /= 26;
        }
    return res;

Rather than using result += result ..., we put the character first then the result.  This provides the answer in the correct order. 

Thanks to vanAmsen for a solution that doesn't reverse the string

Comments

Popular posts from this blog

Wednesday, September 20th

Monday, September 11th

Tuesday, September 19th