Given a string columnTitle that represents the column title as appear in an Excel sheet, return its corresponding column number.
给你一个字符串 columnTitle ,表示 Excel 表格中的列名称。返回该列名称对应的列序号。
输入 | 输出 |
---|---|
columnTitle = "A" | 1 |
columnTitle = "AB" | 28 |
columnTitle = "ZY" | 701 |
columnTitle = "FXSHRXW" | 2147483647 |
这道题类似于26进制转化为十进制的问题,因此可以类比进制转换的“加权求和法”,具体代码如下:
class Solution { public: int titleToNumber(string columnTitle) { int num = 0; for (int i = columnTitle.size() - 1; i >= 0; i--) { num += (columnTitle[i] - 'A' + 1) * pow(26, columnTitle.size() - 1 - i); } return num; } };
考虑到pow函数时间复杂度较高,可利用递推进行求解。代码如下:
class Solution { public: int titleToNumber(string columnTitle) { int num = 0; for (int i = 0; i < columnTitle.size(); i++) { num = columnTitle[i] - 'A' + 1 + num * 26; } return num; } };
对于循环部分,可以用c++11进行优化。代码如下:
class Solution { public: int titleToNumber(string columnTitle) { int num = 0; for (auto element:columnTitle) { num = element - 'A' + 1 + num * 26; } return num; } };