Friday, September 25, 2020

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

Example:

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

Approach: Not much to explain. Its a straight forward case -

        public static string ConvertToTitle(int n)

        {

            string result = string.Empty;        

            while(n > 0)

            {

                --n;

                int remainder = n % 26;

                result = (char)('A' + remainder) + result;

                n = n / 26;

            }

            return result;

        }

No comments:

Post a Comment