lc171.Excel表列序号
约 162 字
预计阅读 1 分钟
正向遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
|
class Solution {
public:
int titleToNumber(string columnTitle) {
// 正向遍历->叠加权重
int ans = 0, n = columnTitle.size();
for(int i = 0; i < n; i++){
ans = columnTitle[i] - 'A' + ans * 26 + 1;
}
return ans;
}
};
|
反向遍历
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
class Solution {
public:
int titleToNumber(string columnTitle) {
// 反向->计算位权重
int ans = 0, n = columnTitle.size();
long long weight = 1;
for(int i = n - 1; i >= 0; i--){
ans += (columnTitle[i] - 'A' + 1) * weight;
weight *= 26;
}
return ans;
}
};
|