class Solution:
def titleToNumber(self, columnTitle: str) -> int:
result = 0
for char in columnTitle:
result = result * 26 + (ord(char) - ord('A') + 1)
return result
class Solution {
public:
int titleToNumber(string columnTitle) {
int result = 0;
for (char c : columnTitle) {
result = result * 26 + (c - 'A' + 1);
}
return result;
}
};
class Solution {
public int titleToNumber(String columnTitle) {
int result = 0;
for (char c : columnTitle.toCharArray()) {
result = result * 26 + (c - 'A' + 1);
}
return result;
}
}
var titleToNumber = function(columnTitle) {
let result = 0;
for (let i = 0; i < columnTitle.length; i++) {
result = result * 26 + (columnTitle.charCodeAt(i) - 'A'.charCodeAt(0) + 1);
}
return result;
};
Given a string columnTitle
that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example, A
corresponds to 1, B
to 2, ..., Z
to 26, AA
to 27, AB
to 28, and so on.
columnTitle
.
At first glance, the problem looks similar to converting a number from one base to another, except instead of digits 0-9, we use letters 'A'-'Z' to represent numbers 1-26. For example, 'A' is 1, 'B' is 2, ..., 'Z' is 26, then 'AA' is 27 (like how 10 is after 9 in decimal).
A brute-force approach might try to enumerate all possible combinations, but that's unnecessary. Instead, we can recognize that this is a "base-26" system, but with no zero digit—'A' represents 1, not 0. This means that for each character, we can multiply the current result by 26 and add the value of the current character.
The challenge is to correctly map each character to its corresponding value and accumulate the result in a way similar to how you convert a string of digits to an integer.
result
) to 0. This will store the final column number.
columnTitle
string from left to right.
ord(char) - ord('A') + 1
(or similar logic in other languages). This maps 'A' to 1, 'B' to 2, ..., 'Z' to 26.
result
by multiplying it by 26 (shifting the previous digits left, as in base conversion) and adding the value of the current character.
result
.
This method is efficient because it processes each character exactly once and uses simple arithmetic.
Let's walk through the example columnTitle = "AB"
:
result = 0
.
Another example: columnTitle = "ZY"
columnTitle
. We process each character once.The problem is a classic example of converting a string representation from a custom base (here, base-26 with letters) to a number. Recognizing the analogy to base conversion allows for a simple, efficient solution that processes each character in the string once. The elegance of this solution comes from its direct mapping of the Excel column system to math we already know, making the implementation short and clear.