题目链接:https://leetcode.com/problems/excel-sheet-column-number/
题目内容:
Related to question Excel Sheet Column Title
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
题目分析:
很常规的题目,跟那些计算数字,字符串类和的题目一样的思路,只是base不一样,在这道题中变成26.一开始我考虑的是如果字符串太长导致整型溢出的情况,并设置为如果这种情况出现就返回整型的最大值。后来ac之后改为整型的测试下,发现两者都能AC,而且少了判断语句之后两者的效率也差不多。下面贴出代码,注释掉的是考虑可能溢出的情况,
class Solution {
public:
int titleToNumber(string s) {
if(s == "") return 0;
else{
/*long sum = 0;
int len = s.size();
for(int i = 0; i < len; i++)
sum = sum*26 + (s[i] - 'A' + 1);
if(sum > (long)INT_MAX) return INT_MAX;
else return (int)sum;*/
int sum = 0;
int len = s.size();
for(int i = 0; i < len; i++)
sum = sum*26 + (s[i] - 'A' + 1);
return sum;
}
}
};