leetcode-171-Excel-Sheet-Column-Number

描述


Related to question Excel Sheet Column Title

Given a column title as appear in an Excel sheet, return its corresponding column number.

For example:

1
2
3
4
5
6
7
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28

分析


实际上就是一个进制转换问题,26进制转10进制,所以,题目Excel Sheet Column Title就是10进制转26进制了。

解决方案1(C++)


1
2
3
4
5
6
7
8
9
10
class Solution {
public:
int titleToNumber(string s) {
int result = 0;
for(int i = 0; i < s.size(); i++){
result = result*26 + (s[i]-'A'+1);
}
return result;
}
};

解决方案2(Python)


1
2
3
4
5
6
7
8
9
10
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
result = 0
for i in s:
result = result*26 + (ord(i)-64)
return result

解决方案3(Golang)


1
2
3
4
5
6
7
8
9
func titleToNumber(columnTitle string) int {
result := 0
for i, multiple := len(columnTitle)-1, 1; i >= 0; i-- {
k := columnTitle[i] - 'A' + 1
result += int(k) * multiple
multiple *= 26
}
return result
}

相关问题


题目来源