本文共 3603 字,大约阅读时间需要 12 分钟。
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A2 -> B3 -> C...26 -> Z27 -> AA28 -> AB
Credits:
Special thanks to @ifanchu for adding this problem and creating all test cases.本质上就是将一个10进制数转换为一个26进制的数
注意:由于下标从1开始而不是从0开始,因此要减一操作。
The Best Answer:
/** * 最好的方式 */ public String convertToTitle2(int n) { String ret = ""; while (n != 0) { ret = (char) ((n - 1) % 26 + 'A') + ret; n = (n - 1) / 26; } return ret; }
再提供一种递归一种非递归的方式,都是Accept!
递归形式:
/** * 递归形式 * * @param n * @return */ public String convertToTitle(int n) { if (n == 0) return ""; if (n <= 26) return intToStr(n); String str = ""; int temp = n % 26; int i = n / 26; if (temp == 0) i--; str += convertToTitle(i); str += intToStr(temp); return str; } public String intToStr2(int x) { switch (x) { case 0: return "A"; case 1: return "B"; case 2: return "C"; case 3: return "D"; case 4: return "E"; case 5: return "F"; case 6: return "G"; case 7: return "H"; case 8: return "I"; case 9: return "J"; case 10: return "K"; case 11: return "L"; case 12: return "M"; case 13: return "N"; case 14: return "O"; case 15: return "P"; case 16: return "Q"; case 17: return "R"; case 18: return "S"; case 19: return "T"; case 20: return "U"; case 21: return "V"; case 22: return "W"; case 23: return "X"; case 24: return "Y"; case 25: return "Z"; } return ""; }
非递归形式:
/** * 非递归形式 * * @param n * @return */ public String convertToTitle1(int n) { if (n == 0) return ""; if (n <= 26) return intToStr(n); String str = ""; int temp = 0; while (n != 0) { temp = (n - 1) % 26; str = intToStr2(temp) + str; n = (n - 1) / 26; } return str; }public String intToStr2(int x) { switch (x) { case 0: return "A"; case 1: return "B"; case 2: return "C"; case 3: return "D"; case 4: return "E"; case 5: return "F"; case 6: return "G"; case 7: return "H"; case 8: return "I"; case 9: return "J"; case 10: return "K"; case 11: return "L"; case 12: return "M"; case 13: return "N"; case 14: return "O"; case 15: return "P"; case 16: return "Q"; case 17: return "R"; case 18: return "S"; case 19: return "T"; case 20: return "U"; case 21: return "V"; case 22: return "W"; case 23: return "X"; case 24: return "Y"; case 25: return "Z"; } return ""; }
自然没有第一种解决巧妙,直接用余数+’A’,这样就可以直接得出需要的结果字符,而不需要用数组或者这种长长的switch语句。
转载地址:http://asvia.baihongyu.com/