




Sponsored
Sponsored
To solve this problem, we use a mathematical approach similar to converting a number to a different base. Here, the base is 26, similar to the English alphabet, where each letter corresponds to a unique representation of a number. This approach involves repeated division by 26 and mapping the remainder to the corresponding letter in the alphabet.
Time Complexity: O(log26(n)), where n is the columnNumber, due to repeated division by 26.
Space Complexity: O(log26(n)), to store the result string.
1using System;
2using System.Text;
3
4public class ExcelConverter {
5    public string ConvertToTitle(int columnNumber) {
6        StringBuilder result = new StringBuilder();
7        while (columnNumber > 0) {
8            columnNumber--;
9            result.Insert(0, (char)((columnNumber % 26) + 'A'));
10            columnNumber /= 26;
11        }
12        return result.ToString();
13    }
14
15    public static void Main(){
16        ExcelConverter ec = new ExcelConverter();
17        Console.WriteLine(ec.ConvertToTitle(28));  // Output: AB
18    }
19}The C# solution uses StringBuilder to efficiently build the result in reverse order by inserting characters at the start. This mimics the base 26 conversion process utilized by Excel column titles.
This approach uses recursion to solve the problem. The function calls itself with the quotient of the column number divided by 26, constructing the result string backwards using the modulo operation to index into the alphabet.
Time Complexity: O(log26(n))
Space Complexity: O(log26(n)), due to the recursive call stack.
1using System;
public class ExcelConverter {
    public string ConvertToTitle(int columnNumber) {
        if (columnNumber <= 0) return string.Empty;
        columnNumber--;
        return ConvertToTitle(columnNumber / 26) + (char)((columnNumber % 26) + 'A');
    }
    public static void Main(){
        ExcelConverter ec = new ExcelConverter();
        Console.WriteLine(ec.ConvertToTitle(28));  // Output: AB
    }
}C# uses recursion to dynamically build the Excel title by breaking down the problem into smaller subproblems, with character values calculated and appended upon exit from each recursion level.