[
math
]
Leetcode 0171. Excel Sheet Column Number
https://leetcode.com/problems/excel-sheet-column-number
Note, that all depends on the place we have some symbol, for example:
for s = DACB:
- We have symbol
Bon the last place, with stands for2 - We have symbol
Con the previous place, which stands for3*26. - We have symbol
Aon the previous place, which stands for1*26*26. - Finally, we have symbol
Don the first place, which stands for4*26*26*26. - What we need to return in this case is
2+3*26+1*26*26+4*26*26*26.
Note, that is it very similar to base 26 numeral system, but not exactly it, here we do not have zeros. All this can be written as oneliner.
Complexity: Time complexity of this oneliner is O(n log n), where n is length of string. We need to iterate over all string and use 26**i. Time complexity can be easily reduced to O(n). Space complexity is O(n), which also can be reduced to O(1). But in this problem n is very small: n<=7, so it will not make a lot of difference
class Solution:
def titleToNumber(self, s):
return sum([(ord(T)-ord("A")+1)*26**i for i,T in enumerate(s[::-1])])
If you like the solution, you can upvote it on leetcode discussion section: Problem 0171