Dare2Solve
The problem is to convert a given Excel column title (as it appears in an Excel sheet) into its corresponding column number. For example, the column title "A"
corresponds to 1
, "AB"
to 28
, and "ZY"
to 701
. The task is to simulate this conversion process and return the correct column number.
Excel column titles are based on a base-26 numeral system, where each letter represents a digit, with 'A'
corresponding to 1
, 'B'
to 2
, and so on up to 'Z'
for 26
. The problem is essentially about converting a string from this custom base-26 system into a decimal number. The conversion is similar to how we convert a number from a numeral system like binary or hexadecimal to a decimal number.
Initialization:
count
initialized to 0
. This will hold the final column number.Iterate Through the Column Title:
'A'
corresponds to 1
, 'B'
to 2
, etc.) by subtracting the ASCII value of 'A'
and adding 1
.count
by multiplying the existing value by 26
(since it's base-26) and then adding the positional value of the current character.Return the Result:
count
variable will contain the final column number.O(n)
, where n
is the length of the column title. Each character in the string is processed once.
O(1)
additional space is required, as the solution only uses a few extra variables for calculations.
class Solution {
public:
int titleToNumber(string columnTitle) {
int count = 0;
for (char c : columnTitle) {
int currentVal = c - 'A' + 1;
count = count * 26 + currentVal;
}
return count;
}
};
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
count = 0
for c in columnTitle:
currentVal = ord(c) - ord('A') + 1
count = count * 26 + currentVal
return count
class Solution {
public int titleToNumber(String columnTitle) {
int count = 0;
for (int i = 0; i < columnTitle.length(); i++) {
int currentVal = columnTitle.charAt(i) - 'A' + 1;
count = count * 26 + currentVal;
}
return count;
}
}
var titleToNumber = function(columnTitle) {
let count = 0;
for(let i=0; i < columnTitle.length; i++){
let currentVal = columnTitle.charCodeAt(i) - "A".charCodeAt(0) +1;
count = count * 26 + currentVal
}
return count;
};