**LeetCode_171 刷题笔记**
1 原题目
Given the name of a column in a Excel Table, return its corresponding column number.
2 题目大意
给定一个Excel表格中的列名称,返回其相应的列序号。
3 题目分析
因为一共是26个字母,所以就是一个二十六进制转十进制的题目
4 基础知识
进制之间的换算
4.1 C的语法
1.POW(x,y)就是#include<math.h>中的函数,意思是x的y次方
2.for(auto ss:s)就是c++的新特性,例如:
S[]={1,2,3,4};
for(auto ss:s)
cout<<ss;
结果就是1234
其中ss就用来在遍历过程中获得容器里的每一个元素
3. ASCII码中,A~Z:65-90
4.2数据结构
没用到
4.3算法
没用到
5 解法
解法1 ©
#include <math.h>
int titleToNumber(char * s){ //s如果=ZY,则s[0]=Z, s[1]=Y
int i,len,pwo;
int ans=0;
len=strlen(s); //len=2
for(i=0;i<len;i++){ //从最高位加起
pwo=pow(26,len-i-1);//i=0,pwo=26;i=1,pwo=1;
ans=(s[i]-64)*pwo+ans; //i=0,ans=(‘z’-64)*26+0=676;i=1,ans=(‘y’-64)*1+676=701
}
return ans;
}
解法2 (c++)
class Solution {
public:
int titleToNumber(string s) { //s=ZY
int res = 0;
for(auto ss : s){ //ss=Z;ss=Y
res = res * 26 + (ss - 64);//res=0+(z-64)=26;res=676+(‘Y’-64)=676+25=701
}
return res;
}
};
6 总结
题目挺简单,没什么大技巧,仔细思考思考就出来了