题目:
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
我的解法:
class Solution {
public:
int titleToNumber(string s) {
int size = s.size();
int count(0);
int p(0);
for(int i = size-1; i >= 0;i--){
count+= (s[i]-'A'+1)*pow(26,p++);
}
return count;
}
};
大神的代码
int titleToNumber(string s) {
return accumulate(s.begin(), s.end(), 0, [](int num, char ch) { return num * 26 + ch - 'A' + 1; }); // 使用了累加函数,
}
这个累加函数的形参表:分别是开始,结尾。和自定义的function,(在这之前还可以有一天个初始值)自定义function中第一个参数是最终的返回值,也是不断累加的值,第二个参数是每次从累加序列里拿取的值