题目:
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
提示:
此题考查的是对N进制数转10进制数的转换。
代码:
我自己的方法是从最低位开始转换,需要用到pow()函数:
class Solution {
public:
int titleToNumber(string s) {
int result = ;
int length = s.length() - ;
for (int i = length; i >= ; --i) {
char c = s.at(i);
result += (int(c)-) * pow(, length-i);
}
return result;
}
};
在论坛中看到了一种更好的方法,直接从最高位转换,代码比我的简洁不少:
class Solution {
public:
int titleToNumber(string s) {
int len = s.size();
int sum = s[] - ;
for (int i = ;i < len; ++i){
sum = sum * + int(s[i] - );
}
return sum;
}
};