171. Excel Sheet Column Number
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
本质:26进制转换为10进制
以下这个例子是错误的,因为比如AB,按字符串的顺序排在第一位的是A而不是B
class Solution {
public:
int titleToNumber(string s) {
int ret = 0;
for(int i = 0; i < s.size(); i ++)
{
int m=pow(26,i);
ret +=(s[i]-'A'+1)*m;
}
return ret;
}
};
正确的是:
class Solution {
public:
int titleToNumber(string s) {
int ret = 0;
int n=s.size();
for(int i = 0; i < n; i ++)
{
int m=pow(26,n-1-i);
ret +=(s[i]-'A'+1)*m;
}
return ret;
}
};
这样也是对的
- class Solution {
- public:
- int titleToNumber(string s) {
- int sum = 0;
- int tmp = 0;
- for (int i = 0; i < s.length(); ++i) {
- tmp = s[i] - 'A' + 1;
- sum = 26 * sum + tmp;
- }
- return sum;
- }
- };