Given a string columnTitle
that represents the column title as appear 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
Example 4:
Input: columnTitle = "FXSHRXW" Output: 2147483647
Constraints:
1 <= columnTitle.length <= 7
columnTitle
consists only of uppercase English letters.columnTitle
is in the range["A", "FXSHRXW"]
.
Solution: Base conversion
Time complexity: O(n)
Space complexity: O(1)
C++
1 2 3 4 5 6 7 8 9 10 11 12 |
// Author: Huahua class Solution { public: int titleToNumber(string s) { int ans = 0; for (int i = s.length() - 1, cur = 0; i >= 0; --i) { cur = cur ? cur * 26 : 1; ans += (s[i] - 'A' + 1) * cur; } return ans; } }; |
Related Problems
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
[…] 花花酱 LeetCode 171. Excel Sheet Column Number […]