题目介绍
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
自己的解法
public class Solution {
public int titleToNumber(String s) {
int num=0;
int max=1;
int length=s.length();
char [] c =s.toCharArray();
int [] a =new int[length];
while(length!=1){
max*=26;
length--;
}
for(int i=0;i<s.length();i++){
a[i]=(int)c[i]-64;
num+=a[i]*max;
max/=26;
}
return num;
}
}
题目的意思是其实就是将26进制转为10进制,每一位有对应的权值从低到高分别是26^0,26^1,26^2等等,再乘以对应为的值加起来就可以。比如说BA=2*26+1*1=53。英文数字对应的值就是相应英文字母的ASCII值减去A的ASCII值再加一。
Hot解法
public class Solution {
public int titleToNumber(String s) {
int result = 0;
for (int i = 0; i < s.length(); i++){
result *= 26;
result += ((s.charAt(i) - 'A') + 1);
}
return result;
}
}
本文介绍了如何将Excel表格中的列标题(如AA、AB等)转换为其对应的列号(如27、28等)。提供了两种解决方案:一种是自行实现的算法,另一种是简洁高效的热门解法。
110

被折叠的 条评论
为什么被折叠?



