題目:
給定一個(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
鏈接:https://leetcode-cn.com/problems/excel-sheet-column-number
思路:
1腿椎、這道題是將26進(jìn)制的數(shù)轉(zhuǎn)換為10進(jìn)制的數(shù)
Python代碼:
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
ret = 0
for item in s:
temp = ord(item)-64
ret = ret*26+temp
return ret
C++代碼:
class Solution {
public:
int titleToNumber(string s) {
int ret=0;
for (char item:s){
int temp = item-64; // A的ascii碼是65
ret = 26*ret+temp;
}
return ret;
}
};