# Question

Formatted question description: https://leetcode.ca/all/168.html

Given an integer columnNumber, return its corresponding column title as it appears in an Excel sheet.

For example:

A -> 1
B -> 2
C -> 3
...
Z -> 26
AA -> 27
AB -> 28
...


Example 1:

Input: columnNumber = 1
Output: "A"


Example 2:

Input: columnNumber = 28
Output: "AB"


Example 3:

Input: columnNumber = 701
Output: "ZY"


Constraints:

• 1 <= columnNumber <= 231 - 1

# Algorithm

For numbers less than 26, then we only need to take the remainder of 26, then subtract 1 and add the character A.

# Code

• 
public class Excel_Sheet_Column_Title {

class Solution {
public String convertToTitle(int n) {

if (n <= 0) {
return "";
}

StringBuilder sb = new StringBuilder();
while (n > 0) {

// @note: key is, not n, but n-1
int remainder = (n - 1) % 26;
sb.insert(0, (char)('A' + remainder)); // @note: reverse order

n = (n - 1) / 26;
}

return sb.toString();
}
}
}

############

class Solution {
public String convertToTitle(int columnNumber) {
StringBuilder res = new StringBuilder();
while (columnNumber != 0) {
--columnNumber;
res.append((char) ('A' + columnNumber % 26));
columnNumber /= 26;
}
return res.reverse().toString();
}
}

• class Solution:
def convertToTitle(self, columnNumber: int) -> str:
res = []
while columnNumber:
columnNumber -= 1
res.append(chr(ord('A') + columnNumber % 26))
columnNumber //= 26
return ''.join(res[::-1])

############

class Solution(object):
def convertToTitle(self, n):
"""
:type n: int
:rtype: str
"""
ans = ""
while n > 0:
y = n % 26
if y == 0:
char = "Z"
n -= 26
else:
char = chr(ord("A") + y - 1)
ans += char
n = n / 26
return ans[::-1]


• func convertToTitle(columnNumber int) string {
res := []rune{}
for columnNumber != 0 {
columnNumber -= 1
res = append([]rune{rune(columnNumber%26 + int('A'))}, res...)
columnNumber /= 26
}
return string(res)
}


• function convertToTitle(columnNumber: number): string {
let res: string[] = [];
while (columnNumber > 0) {
--columnNumber;
let num: number = columnNumber % 26;
res.unshift(String.fromCharCode(num + 65));
columnNumber = Math.floor(columnNumber / 26);
}
return res.join('');
}


• public class Solution {
public string ConvertToTitle(int columnNumber) {
StringBuilder res = new StringBuilder();
while (columnNumber != 0) {
--columnNumber;
res.Append((char) ('A' + columnNumber % 26));
columnNumber /= 26;
}
return new string(res.ToString().Reverse().ToArray());
}
}