Excel Sheet Column Number
Total Accepted: 54683 Total Submissions: 140674 Difficulty: Easy
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
思路:
假设num是一个五位数ABCDE.
num=A*26^4+B*26^3+c*26^2+D*26+E*1;
radix作为基数,初始化为1,每次循环*26;
class Solution {
public:
int titleToNumber(string s) {
int len=s.length();
if(len==0){
return 0;
}
int num=0;
int radix=1;
for(int i=len-1;i>=0;i--){
num+=radix*(s[i]-'A'+1);
radix*=26;
}
return num;
}
};