Excel表列序号题解,这个和罗马数字转换比较类似,都是比较实用的题。
下面是题解,可以参考
package easy;
import java.util.HashMap;
import java.util.Map;
public class TitleToNumber {
public static void main(String[] args) {
System.out.println(new TitleToNumber().titleToNumber("Z"));
}
public int titleToNumber1(String columnTitle) {
Map<Character,Integer> char2num=new HashMap<>();
for (int i = 0,j=1; i < 26; i++,j++) {
char2num.put((char)('A'+i),j);
}
char[] chars = columnTitle.toCharArray();
int result=0;
int power=1;
for (int i = chars.length - 1; i >= 0; i--) {
result+=char2num.get(chars[i])*power;
power*=26;
}
return result;
}
public int titleToNumber2(String columnTitle) {
char[] chars = columnTitle.toCharArray();
int result=0;
int power=1;
for (int i = chars.length - 1; i >= 0; i--) {
result+=(chars[i]-'A'+1)*power;
power*=26;
}
return result;
}
public int titleToNumber(String columnTitle) {
int result=0;
int power=1;
char m='A'-1;
for (int i = columnTitle.length() - 1; i >= 0; i--) {
result+=(columnTitle.charAt(i)-m)*power;
power*=26;
}
return result;
}
}