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:
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
解决
简单的想法就是将字符串遍历,将对应的字母转化为数字,再分别按照规律加起来。类似于16进制。
AA => A(1)A(1) => 1 * 26 + 1 = 27
AB => A(1)B(2) => 1 * 26 + 2 = 28
class Solution {
public:
int titleToNumber(string s) {
int result = 0;
int len = s.length();
for (int i = 0; i < len; i++) {
result = (s[i] - 'A' + 1) + result * 26;
}
return result;
}
};