Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """
- 168. Excel Sheet Column Title & 171. Excel Sheet Column Number
- 这两道题其实是一道题。
- 想法其实在这个讨论的帖子里面。 https://leetcode.com/problems/excel-sheet-column-title/discuss/51404/Python-solution-with-explanation
- Now we can see that ABCD=A×26³+B×26²+C×26¹+D=1×26³+2×26²+3×26¹+4
- But how to get the column title from the number? We can't simply use the n%26 method because:
- ZZZZ=Z×26³+Z×26²+Z×26¹+Z=26×26³+26×26²+26×26¹+26
- We can use (n-1)%26 instead, then we get a number range from 0 to 25.
- """
- """
- 168. Excel Sheet Column Title 这道题的难点在于不能 n % 26 要用 (n-1) % 26
- """
- class Solution:
- def __init__(self):
- self.apl = {}
- self.w = 65
- for i in range(0, 26):
- self.apl[i] = chr(self.w)
- self.w += 1
- def convertToTitle(self, n):
- """
- :type n: int
- :rtype: str
- """
- res = ""
- while n > 0:
- tmp = self.apl[(n-1) % 26]
- res = tmp + res
- n = (n-1) // 26
- return res
- """
- 171. Excel Sheet Column Number
- 这道题就是反向求一个 26 进制的数字 => 10进制的数字
- ABCD=A×26³+B×26²+C×26¹+D=1×26³+2×26²+3×26¹+4
- """
- class Solution:
- def __init__(self):
- self.apl = {}
- self.c = 65
- for i in range(1, 27):
- self.apl[chr(self.c)] = i
- self.c += 1
- def titleToNumber(self, s: str) -> int:
- res = 0
- p = len(s) - 1
- i = 0
- while i < len(s):
- tmp = self.apl[s[p-i]]
- res += tmp * (26**i)
- i += 1
- return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement