171 Excel Sheet Column Number Excel表列序號(hào)
Description:
Given a 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
...
Example:
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701
題目描述:
給定一個(gè)Excel表格中的列名稱(chēng)冰木,返回其相應(yīng)的列序號(hào)切省。
例如省撑,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例:
示例 1:
輸入: "A"
輸出: 1
示例 2:
輸入: "AB"
輸出: 28
示例 3:
輸入: "ZY"
輸出: 701
思路:
相當(dāng)于 26進(jìn)制轉(zhuǎn)化為 10進(jìn)制
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(1)
代碼:
C++:
class Solution
{
public:
int titleToNumber(string s)
{
int result = 0;
for (auto c : s)
{
result *= 26;
result += c - 'A' + 1;
}
return result;
}
};
Java:
class Solution
{
public int titleToNumber(String s)
{
int result = 0;
for (char c : s.toCharArray()) {
result *= 26;
result += c - 'A' + 1;
}
return result;
}
}
Python:
class Solution:
def titleToNumber(self, s: str) -> int:
result = 0
for i in s:
result *= 26
result += ord(i) - ord('A') + 1
return result