Question
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
Analysis
A | AA | BA | …… | ZA | …… |
---|---|---|---|---|---|
…… | …… | …… | …… | …… | …… |
Z | AZ | BZ | …… | ZZ | …… |
26 | 1*26+26 | 2*26+26 | …… | 26*26+26 | …… |
Code
#include<iostream>
#include<string.h>
#include<math.h>
using namespace std;
class Solution {
public:
int titleToNumber(string s) {
int sum = 0;
for (int i = 0; i < s.length(); i++) {
sum += (s[i] - 'A' + 1)*pow(26, s.length() - i - 1);
}
return sum;
}
};
int main() {
Solution so;
string s = "BZ";
cout << so.titleToNumber(s) << endl;
system("pause");
return 0;
}