C#: Implementation handles a billion columns

  • 0

    There are much more efficient solutions out there that can handle a 2 character column name, but this implementation will handle up to a billion columns and is limited only by Int32.MaxValue.

        public string ConvertToTitle(int n)
            // Initialization
            var output = new char[8];   // This should be big enough for the billionth column.
            // Write each digit in the column name from the least to the most significant digit.
            int i = 0;  // Number of characters in the column name
                output[i++] = alphabet[n % 26];
                n = (n - 1) / 26;
            while (n > 0);
            // So far, the column name has been build backwards,
            // so we need to reverse the order to build up the string correctly.
            Array.Reverse(output,0, i);
            return new string(output, 0, i);

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.