Excel Sheet Column Number
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
方法一:
例如输入ABCD;
输出的值为:1 * 26 * 26 * 26 + 2 * 26 * 26 + 3 * 26 + 4:
#include<iostream>
#include<string>
using namespace std;
int titleToNumber(string s) {
int sum = 0;
int val;
int x;
int j;
int len = s.length();
for(int i = len; i > 0; i--)
{
x = 1;
j = i;
while( j > 1)
{
x = x * 26;
j--;
}
val = ( s[len-i] - 'A' + 1) * x;
sum = sum + val;
}
return sum;
}
int main(){
string a;
cin >> a;
cout << titleToNumber(a);
}
方法二:
例如输入ABCD;
有方法一变式输出:
(((1 * 26 ) + 2 ) * 26 ) + 3 ) * 26 + 4
所以titleToNumber函数可以改写为:
int titleToNumber(string s) {
int val = 0;
for (int i = 0; i < s.length(); ++i) {
val = val*26 + (s[i]- 'A' + 1);
}
return val;
}