给定一个正整数,返回相应的列标题,如Excel表中所示。
样例
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
解题思路:
是1348. Excel Sheet Column Number的变形,本质仍然是一个进制转换问题,但是需要注意map中对应的是0-25, 而实际中是1-26,这中间的转换需搞明白。
public class Solution {
/**
* @param n: a integer
* @return: return a string
*/
public String convertToTitle(int n) {
// write your code here
HashMap<Integer, Character> map = new HashMap<>();
for(int i=0; i<26; i++)
map.put(i, (char)('A'+i));
StringBuilder str = new StringBuilder();
while(n != 0){
str.insert(0,map.get((n-1)%26));
n = (n-1)/26;
}
return str.toString();
}
}
本文介绍了一种将正整数转换为类似Excel列标题的算法实现。通过使用HashMap存储字符映射,配合进制转换思想,实现了从数字到列标题的高效转换。文章提供了完整的Java代码示例。
686

被折叠的 条评论
为什么被折叠?



