首页 > 代码库 > LeetCode171——Excel Sheet Column Number

LeetCode171——Excel Sheet Column Number

题目

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 

Credits: Special thanks to @ts for adding this problem and creating all test cases.

int titleToNumber(string s) {

}

题目大意

给定电子表上的一栏标题,返回对应的数字。

实现

int titleToNumber(string s) {
    int val = 0;
    for (int i = 0; i < s.length(); ++i) {
        val += (s[i]- ‘A‘ + 1) * static_cast<int>(pow((double)26, (int)(s.length() - 1 -i))); 
    }
    return val;    
}

当然,也可以不使用pow函数。比如下面这种做法:

int titleToNumber(string s) {
    int val = 0;
    for (int i = 0; i < s.length(); ++i) {
        val = val*26 + (s[i]- ‘A‘ + 1);
    }
    return val;    
}

LeetCode171——Excel Sheet Column Number