171. Excel Sheet Column Number

Andreea
May 24, 2021

Given a string columnTitle that represents the 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: columnTitle = "A"
Output: 1

Example 2:

Input: columnTitle = "AB"
Output: 28

Example 3:

Input: columnTitle = "ZY"
Output: 701

Example 4:

Input: columnTitle = "FXSHRXW"
Output: 2147483647
class Solution {
public:
int titleToNumber(string columnTitle) {

int total = 0;
reverse(columnTitle.begin(), columnTitle.end());
for(int i=0; i<columnTitle.length(); i++){

int tmp = pow(26, i);
total += (columnTitle[i]-'A'+1)*tmp;

}
return total;
}
};

A = 1

CA = 26*3 + 1

(類似於26進位的概念)

AAA = 26*26*1 + 26*1 + 1

ACD = 26*26*1 +26*3 + 4

--

--