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.
1#include <iostream>
2#include <string>
3
4int titleToNumber(const std::string& columnTitle) {
5 int result = 0;
6 for (char c : columnTitle) {
7 result = result * 26 + (c - 'A' + 1);
8 }
9 return result;
10}
11
12int main() {
13 std::cout << titleToNumber("ZY") << std::endl;
14 return 0;
15}
Similar to the C solution, we use a loop to process each character, updating the result using base-26 conversion logic. The C++ string class is used for convenient character iteration.
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.