171. Excel Sheet Column Number
Math, String ·Problem Statement
link: https://leetcode.com/problems/excel-sheet-column-number/ https://leetcode.cn/problems/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:
A -> 1 B -> 2 C -> 3 … Z -> 26 AA -> 27 AB -> 28 …
Example:
Input: columnTitle = "A"
Output: 1
Input: columnTitle = "AB"
Output: 28
Input: columnTitle = "ZY"
Output: 701
Solution Approach
The solution splits version strings into individual components, converts them to integers, and performs a straightforward comparison.
Algorithm
- Splitting: Break version1 and version2 on dots (‘.’).
- Comparison: Convert components to integers, using 0 for absent values, and compare.
- Result: Return -1, 1, or 0 based on the comparison outcome.
Implement
class Solution:
def titleToNumber(self, columnTitle: str) -> int:
res = 0
for c in columnTitle:
res = res * 26 + ord(c) - 64
return res