题目介绍
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;
}
}