Leetcode 171. Excel Sheet Column Number
Given a string columnTitle
that represents the column title as appears in an Excel sheet, return its corresponding column number. For example:
columnTitle
string?This problem is analogous to converting a number from a base-26 numeral system to a decimal (base-10) numeral system.
result = 0
.result
with the current character’s positional value.result
.#include <iostream>
#include <string>
int titleToNumber(const std::string& columnTitle) {
int result = 0;
for (char c : columnTitle) {
int value = c - 'A' + 1;
result = result * 26 + value;
}
return result;
}
int main() {
std::string columnTitle = "AB"; // Example input
std::cout << "The column number is: " << titleToNumber(columnTitle) << std::endl;
return 0;
}
n
is the length of the columnTitle
string. Each character is processed once.This method ensures that the algorithm runs efficiently even for longer column titles, adhering to a linear time complexity.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?