两道相关联的题目,一个是将数字转换为26进制,一个是将26进制表示方法转换为10进制
第一次觉得java好慢。
public class Solution { public String convertToTitle(int n) { StringBuilder sb = new StringBuilder(); while (n > 0) { int apd = n % 26; char c; if (apd == 0) { c = 'Z'; n = n / 26 - 1; } else { c = (char) (apd + 'A' - 1); n = n / 26; } sb.append(c); } return sb.reverse().toString(); } }
public class Solution { public int titleToNumber(String s) { HashMap<Character, Integer> map = new HashMap<Character, Integer>(); char c = 'A'; for(int i=1;i<=26;++i){ map.put(c,i); c += 1; } int result = 0; int i = s.length()-1; int t = 0; while(i >= 0){ char curr = s.charAt(i); result = result + (int) Math.pow(26, t) * map.get(curr); t++; i--; } return result; } }
Math.pow(底数,几次方) 如:double a=2.0; double b=3.0; double c=Math.pow(a,b); 就是2的三次方是多少; c最终为8;