Sponsored
Sponsored
This approach involves treating each character of the column title string as a digit in a base-26 number system. We iterate over the string from left to right, calculating its contribution to the overall number at each step by multiplying with an appropriate power of 26.
Time Complexity: O(n), where n is the length of the column title.
Space Complexity: O(1), as no additional space is used that scales with input size.
1def titleToNumber(columnTitle: str) -> int:
2 result = 0
3 for c in columnTitle:
4 result = result * 26 + (ord(c) - ord('A') + 1)
5 return result
6
7# Example usage
8title = "ZY"
9print(titleToNumber(title))
The Python solution leverages the built-in ord() function to convert characters to numbers. We iterate through each character and apply base-26 numeric logic to compute the final result.
This approach uses recursion to compute the column number. Starting from the first character, the function recursively converts the rest of the string and adds the current character's contribution by treating it as a digit in a 26-based number system. This implements a divide-and-conquer strategy.
Time Complexity: O(n)
Space Complexity: O(n), due to recursion stack space.
1
class Solution {
public int TitleToNumberRec(string columnTitle, int index) {
if (index == columnTitle.Length)
return 0;
int current = columnTitle[index] - 'A' + 1;
return current + 26 * TitleToNumberRec(columnTitle, index + 1);
}
public int TitleToNumber(string columnTitle) {
return TitleToNumberRec(columnTitle, 0);
}
static void Main() {
Solution sol = new Solution();
Console.WriteLine(sol.TitleToNumber("ZY"));
}
}
C# utilizes a recursive method to calculate the number, using a recursive function that sums the value of each character based on its significance in a base-26 number system.