给定一个Excel表格中的列名称,返回其相应的列序号。
例如,
A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...
示例 1:
输入: “A”
输出: 1
示例 2:
输入: “AB”
输出: 28
示例 3:
输入: “ZY”
输出: 701
这题是前面那个题的反向操作,思路也很简单,就是转成ascii码就行,然后python很容易就实现了,可是C++调了好久。。。 问题出在string类的用法上 掌握的太不熟练了,各种操作都是现场试现场查。。。
string 类常用的操作和容器不一样,所以不要每次都拿 pop什么的了。。 还有一点就是迭代器 end指向的是尾后,怪不得一般都用begin迭代。。。但是这个倒序也没办法了 记得先end–再使用
还有就是有的测试用例会溢出。。int位数不够用,改成long long就OK
附上代码
C++实现
class Solution {
public:
int titleToNumber(string s) {
int base = 'A'-1;
long long sum = 0;
long long bit = 1;
int res = 0;
auto end = s.end();
while(s.begin()!=end){
end--;
int end_num = *end;
res = end_num-base;
sum = sum + res*bit;
bit *= 26;
}
return sum;
}
};
python3实现
class Solution:
def titleToNumber(self, s: str) -> int:
base = ord('A')-1
sum_res = 0
bit = 1
for i in range(len(s)):
res = s[len(s)-i-1]
res_n = ord(res)-base
sum_res += bit*res_n
bit *=26
return sum_res