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
This recursive solution defines a helper function that processes the current character and recursively calls itself to handle the rest of the string. The base case is when the end of the string is reached.