原题:
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A
2 -> B
3 -> C
...
26 -> Z
27 -> AA
28 -> AB
思路:这题的本质是考察如何将10进制的整数转化为26进制,只是用excel的背景包装了一下。按照正常进制转换的思路写出代码即可。因为要求输出的是字符串序列表示的excel标题,所以需要用一个数组保存26个字母。
代码(Java):
public class Solution {
public String convertToTitle(int n)
{
if(n<0)
{
return null;
}
String [] letters = {"A","B","C","D","E",
"F","G","H","I","J",
"K","L","M","N","O",
"P","Q","R","S","T",
"U","V","W","X","Y",
"Z",};
String result = "";
while(n>0)
{
int temp = (n-1)%26 + 1; //求余,这里不能用n%26,否则26和0无法区分
String singleLetter = letters[temp-1]; //按照数组索引取出相应的字母
result = singleLetter + result ; //字符串拼接
n = (n - temp)/26;
}
return result;
}
}
相关题目:
leetcode-Excel Sheet Column Number