168. Excel Sheet Column Title
Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.
For example:
A -> 1
B -> 2
C -> 3
…
Z -> 26
AA -> 27
.AB -> 28
…
Example 1:
Input: columnTitle = “A”
Output: 1
Example 2:
Input: columnTitle = “AB”
Output: 28
Example 3:
Input: columnTitle = “ZY”
Output: 701
Constraints:
- 1 <= columnTitle.length <= 7
- columnTitle consists only of uppercase English letters.
- columnTitle is in the range [“A”, “FXSHRXW”].
From: LeetCode
Link: 171. Excel Sheet Column Number
Solution:
Ideas:
- The function titleToNumber takes a string columnTitle as input.
- It initializes an integer result to 0.
- It iterates over each character in the string. For each character, it updates the result by multiplying the current result by 26 (since there are 26 letters in the alphabet) and adding the position of the current character in the alphabet (calculated as *columnTitle - ‘A’ + 1).
- The function returns the final result, which is the corresponding column number.
Code:
int titleToNumber(char* columnTitle) {
int result = 0;
while (*columnTitle) {
result = result * 26 + (*columnTitle - 'A' + 1);
columnTitle++;
}
return result;
}