171. 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
...
Example 1:
Input: "A"
Output: 1
Example 2:
Input: "AB"
Output: 28
Example 3:
Input: "ZY"
Output: 701
方法1:
思路:
对于第i位相当于(s[0] -`A` + 1) * 26^0 + (s[1] -`A` + 1) * 26^1 +… (s[i] -`A` + 1) * 26^i 。
但是这个方法explicitly累计了base,最后多出来的一次其实并不需要,但是造成了overflow,只能用long来过渡。
class Solution {
public:
int titleToNumber(string s) {
int n = 0;
long base = 1;
for (int i = s.size() - 1; i >= 0; i--){
char a = s[i - 1];
n += (a - 'A' + 1) * base;
base *= 26;
}
return n;
}
};
在discussion看到比较简洁并且不需要long的做法,利用了n本身起到base的效果。可以拓展到其他power series的情况。每次向后遍历一位相当于对之前的数字在26进制上进一位。
class Solution {
public:
int titleToNumber(string s) {
int result = 0;
for (char c: s){
result = result * 26 + (c - 'A' + 1);
}
return result;
}
};