171. [LeetCode]Excel Sheet Column Number [easy] (java)

### 题目描述:

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 

题目大意:

相关题目:Excel 表格列标题

给定一个出现在Excel表格中的列标题,返回其对应的列号。

样例如题目描述。

解题思路:

26进制转化为10进制

Python代码:

1
2
3
4
5
6
7
8
class Solution:
# @param s, a string
# @return an integer
def titleToNumber(self, s):
  ans = 0
  for e in s:
      ans = ans * 26 + ord(e) - ord('A') + 1
  return ans

Java代码:

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