LeetCode 171: Excel Sheet Column Number
LeetCode 171 Solution Explanation
Explanation:
To convert the Excel sheet column title to its corresponding column number, we can iterate through the characters in the title from right to left. At each step, we calculate the value of the current character and add it to the result by multiplying the previous result by 26. This is because there are 26 letters in the English alphabet. Finally, we return the accumulated result as the column number.
Algorithm:
- Initialize a variable
result
to 0. - Iterate through the characters in the column title from right to left.
- At each step, calculate the value of the current character by subtracting 'A' from it and adding 1.
- Update the
result
by multiplying it by 26 and adding the value of the current character. - Return the final
result
as the column number.
Time Complexity: O(n) where n is the length of the column title.
Space Complexity: O(1)
:
LeetCode 171 Solutions in Java, C++, Python
class Solution {
public int titleToNumber(String columnTitle) {
int result = 0;
for (int i = 0; i < columnTitle.length(); i++) {
int value = columnTitle.charAt(i) - 'A' + 1;
result = result * 26 + value;
}
return result;
}
}
Interactive Code Editor for LeetCode 171
Improve Your LeetCode 171 Solution
Use the editor below to refine the provided solution for LeetCode 171. Select a programming language and try the following:
- Add import statements if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.
Loading editor...