171. Excel Sheet Column Number
171. Excel Sheet Column Number
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 ...
Example 1:
Input: "A" Output: 1
Example 2:
Input: "AB" Output: 28
Example 3:
Input: "ZY" Output: 701
这个,看完题目思路就很清晰了,完成一个26进制数转10进制数的算法,根据进制转换公式可知
AA = 1*26^(2-1) + 1*26^(1-1) = 27,根据这个思路可写出代码:
public int titleToNumber(String s) { char[] str = s.toCharArray(); int sum = 0; for (int i = str.length, j = 0; i > 0; i--, j++) { sum += (int) (dictionary.get("" + str[j]) * Math.pow(26, i - 1)); } return sum; } private static Map<String, Integer> dictionary = new HashMap<String, Integer>() { { put("A", 1); put("B", 2); put("C", 3); put("D", 4); put("E", 5); put("F", 6); put("G", 7); put("H", 8); put("I", 9); put("J", 10); put("K", 11); put("L", 12); put("M", 13); put("N", 14); put("O", 15); put("P", 16); put("Q", 17); put("R", 18); put("S", 19); put("T", 20); put("U", 21); put("V", 22); put("W", 23); put("X", 24); put("Y", 25); put("Z", 26); } };
提交答案后发现,不能每次都piapia直接写,仔细考虑考虑能少写不少代码,s中的某一位很简单就能得到数字和字母的映射关系,这个map写的手累不说,看起来也很傻😂。
public int titleToNumber(String s) { int sum = 0; for (int i = s.length(), j = 0; i > 0; i--, j++) { sum += ((s.charAt(j)) - 'A' + 1) * Math.pow(26, i - 1); } return sum; }