leetcode:Excel Sheet Column Number

时间:2023-03-09 16:03:21
leetcode: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进制数字
class Solution {
public:
int titleToNumber(string s) {
int n=0;
for(int i=0;i<s.size();i++)
{
n=n*26+(s[i]-'A'+1);
return n;
}
}
};

  编译的时候开始总是出现Line 4: stray ‘\357’ in program错误,后来才知道不小心在程序中打入了全角字符。

其他解法:

A C++ solution Runtime: 0ms

class Solution {
public:
int titleToNumber(string s) {
int res = 0;
for(int i=0; i<s.length(); i++){
int exp = s[i] - 'A' + 1;
res = exp * pow(26, s.length() - i -1) + res;
}
return res;
}
};