您的位置:首页 > 其它

Excel Sheet Column Number

2015-01-13 13:07 190 查看
https://oj.leetcode.com/problems/excel-sheet-column-number/

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) {
Map map = new HashMap();
map.put('A', 1);
map.put('B', 2);
map.put('C', 3);
map.put('D', 4);
map.put('E', 5);
map.put('F', 6);
map.put('G', 7);
map.put('H', 8);
map.put('I', 9);
map.put('J', 10);
map.put('K', 11);
map.put('L', 12);
map.put('M', 13);
map.put('N', 14);
map.put('O', 15);
map.put('P', 16);
map.put('Q', 17);
map.put('R', 18);
map.put('S', 19);
map.put('T', 20);
map.put('U', 21);
map.put('V', 22);
map.put('W', 23);
map.put('X', 24);
map.put('Y', 25);
map.put('Z', 26);

char[] chars = s.toCharArray();
int result = 0;
for(int i = 0; i < chars.length; i++){
int result_here = (Integer)map.get(chars[i]);
for(int j = 0; j < chars.length - i -1; j++)
result_here *= 26;
result += result_here;
}
return result;
}
}


其实就是26进制转为10进制。这里26进制不太严谨,因为并非0-25。

改进点,可以直接考虑字母代表的是进制数字就是s.charAt(i) - 'A' + 1。而免去前面赋值的过程。

update 2015/07/01:

如此简单而已

public class Solution {
public int titleToNumber(String s) {
int res = 0;
for(int i = 0; i < s.length(); i++) {
res = res * 26 + s.charAt(i) - 'A' + 1;
}
return res;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: