0%

[Leetcode]171. Excel Sheet Column Number (C++)

题目描述

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

例子

例子 1

Input: "A"
Output: 1

例子 2

Input: "AB"
Output: 28

例子 3

Input: "ZY"
Output: 701

Note

  • 1 <= s.length <= 7
  • s consists only of uppercase English letters.
  • s is between “A” and “FXSHRXW”.

解题思路

这道题比较简单,考虑成字母表示的 26 进制转换即可,从最低位(字符串最末尾)开始,每一位呈上相应的系数 pow(26, i) 相加即可,避免重复计算 pow() 可以用一个变量依次乘,注意由于位数可能会很长,系数类型最好用 long,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int titleToNumber(string s) {

int number = 0;
long coeff = 1;
for (int i = s.length() - 1; i >= 0; i--) {
number += (s[i] - 'A' + 1) * coeff;
coeff *= 26;
}

return number;

}
};
  • 时间复杂度: O(s.length)
  • 空间复杂度: O(1)