168. Excel Sheet Column Title
Question:
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:
Input: 1
Output: "A"
Input: 28
Output: "AB"
Input: 701
Output: "ZY"
Source code:
Version 1
Idea:
According to the ASCII talbe, if you want to get A~Z character, you need 65-90 demical number to convert it.
If the input is n = 26
, you use %26
to get the remainder is zero, then it is converted to character you will attain 'A'
, but a correct answer is 'Z'
. So, n minus 1 is important before you get the remainder at 6 line.
Next step, you can convert int to character directly. Notice: +65
is same as 'A'
.
At 8 line, (n - 1)/26
as a carry condition every time until n will be 0.
1 | class Solution { |