2023年5月17日 星期三

5/17 每日一題(26進位)

 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 1:

Input: columnTitle = "A"
Output: 1

Example 2:

Input: columnTitle = "AB"
Output: 28

Example 3:

Input: columnTitle = "ZY"
Output: 701

 

Constraints:

  • 1 <= columnTitle.length <= 7
  • columnTitle consists only of uppercase English letters.
  • columnTitle is in the range ["A", "FXSHRXW"].

class Solution:
    def titleToNumber(self, columnTitle: str) -> int:
        #chr(65)="A"
        #ord("A")=65
        n=len(columnTitle)-1 #最高位數次方 (例如200=2*[10**2],len(200)=3)
        point=0
        for i in columnTitle:
            x=26**n
            a=ord(i)-64
            point += a*x  #(ex:201=2*10**2 + 0*10**1 + 2*10**0)
            n -= 1
        return point
-----------------------------------------------



標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁