题目原址
https://leetcode.com/problems/excel-sheet-column-title/description/
题目描述
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
…
Example 1:
Input: 1
Output: “A”
Example 2:
Input: 28
Output: “AB”
Example 3:
Input: 701
Output: “ZY”
解题思路
这个题与之前的171题是相反的过程,但是解题思路与之前的题完全不同,相比于之前的题,这个题相对简单一些。
因为是从数映射的字符,一共有26个字符,1对应A……26对应Z,27对应AA,所以这里边把Z放在字符数组的第一个,然后A……Y依次放在第2……26个位置。
从0–26个数都是有效的字符,因此n依次对26取余数,然后得到的结果对应字符数组相应的余数位置,如果I = 0就说明是Y,则将其n的值-1。
AC代码
class Solution {
public String convertToTitle(int n) {
String ret = "";
char[] s = {'Z','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'};
while(n > 0) {
int i = n % 26;
ret = s[i] + ret ;
if(i == 0)
n = n - 1;
n = n / 26;
}
return ret;
}
}