大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
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
...
Input: columnTitle = "A"
Output: 1
Input: columnTitle = "AB"
Output: 28
Input: columnTitle = "ZY"
Output: 701
Input: columnTitle = "FXSHRXW"
Output: 2147483647
1 <= columnTitle.length <= 7
columnTitle
consists only of uppercase English letters.columnTitle
is in the range ["A", "FXSHRXW"]
.首先先簡單的翻譯一下題目
給一個columnTitle
的String,他代表的是excel中的column,要把他轉換成對應的數字。
作法大致上是這樣
columnTitle
的長度-1再減掉for loop跑迴圈時的index,加總起來就得到最後的結果啦。class Solution:
def titleToNumber(self, columnTitle: str) -> int:
# ascii "A"=65, "Z"=90
# ord() string to ascii
# chr() ascii to string
# AZ => A*26^1 + Z*26Z^0
# AB => A*26 + B*1
column = 0
for index in range(len(columnTitle)):
column += (ord(columnTitle[index])-64) * (26**(len(columnTitle)-1-index))
return column
int titleToNumber(char * columnTitle){
long int column = 0;
long int multiple = 1;
for (int index=strlen(columnTitle)-1 ; index>=0 ; index--){
column += (( (int)(columnTitle[index])-64 ) * multiple);
multiple *= 26;
}
return column;
}
大家明天見