Excel Sheet Column Number

171.Excel Sheet Column Number

Given a string columnTitle that represents the column title as appears in an Excel sheet, return its corresponding column number.

For example:

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

Example 1:

1
2
Input: columnTitle = "A"
Output: 1

Example 2:

1
2
Input: columnTitle = "AB"
Output: 28

Example 3:

1
2
Input: columnTitle = "ZY"
Output: 701

时间复杂度:O(n)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
public:
int titleToNumber(string columnTitle) {
long n = pow(26, (columnTitle.size() - 1));
int ans = 0;
for (char c : columnTitle) {
ans += (c - 'A' + 1) * n;
n /= 26;
}
return ans;
}
};