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
C++实现代码:
#include<iostream> #include<string> #include<cstring> #include<cmath> using namespace std; class Solution { public: int titleToNumber(string s) { int sum=0; int n=strlen(s.c_str()); int i; int count=n-1; for(i=0;i<n;i++) { double p=pow(26,count); sum+=(s[i]-'A'+1)*p; count--; } return sum; } }; int main() { Solution s; cout<<s.titleToNumber("AB")<<endl; }
注意:其中求指数时需要使用的类型是double类型,如果使用int类型,结果不对。。