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
可以看作把一个26进制的数转化为十进制,根据公式即可。
public int titleToNumber(String s) {
if(s.length()==0) return 0;
int sum = 0;
int len = s.length();
for(int i=0;i<len;i++){
char c = s.charAt(i);
int num = c-'A'+1;
sum = (int) (sum + num*(Math.pow(26,len-i-1)));
}
return sum;
}
上面需要调用数学函数,需要时间开销。但可以不必,如“ABCD”即可视为((1*26+2)*26+3)*26+4.
public int titleToNumber1(String s){
if(s.length()==0) return 0;
int sum =0;
int len = s.length();
for(int i=0;i<len;i++){
char c = s.charAt(i);
int num = c-'A'+1;
sum = sum*26+num;
}
return sum;
}