Advertisement
jinhuang1102

168. Excel Sheet Column Title & 171. Excel Sheet Column Numb

Mar 22nd, 2019
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.76 KB | None | 0 0
  1. """
  2. 168. Excel Sheet Column Title & 171. Excel Sheet Column Number
  3. 这两道题其实是一道题。
  4. 想法其实在这个讨论的帖子里面。 https://leetcode.com/problems/excel-sheet-column-title/discuss/51404/Python-solution-with-explanation
  5.  
  6. Now we can see that ABCD=A×26³+B×26²+C×26¹+D=1×26³+2×26²+3×26¹+4
  7. But how to get the column title from the number? We can't simply use the n%26 method because:
  8. ZZZZ=Z×26³+Z×26²+Z×26¹+Z=26×26³+26×26²+26×26¹+26
  9. We can use (n-1)%26 instead, then we get a number range from 0 to 25.
  10. """
  11. """
  12. 168. Excel Sheet Column Title 这道题的难点在于不能 n % 26 要用 (n-1) % 26
  13. """
  14. class Solution:
  15.     def __init__(self):
  16.         self.apl = {}
  17.         self.w = 65
  18.         for i in range(0, 26):
  19.             self.apl[i] = chr(self.w)
  20.             self.w += 1
  21.            
  22.     def convertToTitle(self, n):
  23.         """
  24.        :type n: int
  25.        :rtype: str
  26.        """
  27.         res = ""
  28.         while n > 0:
  29.             tmp = self.apl[(n-1) % 26]
  30.             res = tmp + res
  31.             n = (n-1) // 26
  32.            
  33.         return res
  34.  
  35. """
  36. 171. Excel Sheet Column Number
  37. 这道题就是反向求一个 26 进制的数字 => 10进制的数字
  38. ABCD=A×26³+B×26²+C×26¹+D=1×26³+2×26²+3×26¹+4
  39. """
  40. class Solution:
  41.     def __init__(self):
  42.         self.apl = {}
  43.         self.c = 65
  44.         for i in range(1, 27):
  45.             self.apl[chr(self.c)] = i
  46.             self.c += 1
  47.    
  48.     def titleToNumber(self, s: str) -> int:
  49.         res = 0
  50.         p = len(s) - 1
  51.         i = 0
  52.         while i < len(s):
  53.             tmp = self.apl[s[p-i]]
  54.             res += tmp * (26**i)
  55.             i += 1
  56.            
  57.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement