Excel Sheet Column Title
Problem
Given a positive integer column number, return its Excel column title (A, B, …, Z, AA, AB, …, ZZ, AAA, …).
columnNumber = 701"ZY"def convert_to_title(n):
out = []
while n > 0:
n -= 1
out.append(chr(ord('A') + n % 26))
n //= 26
return "".join(reversed(out))
function convertToTitle(n) {
const out = [];
while (n > 0) {
n--;
out.push(String.fromCharCode(65 + (n % 26)));
n = Math.floor(n / 26);
}
return out.reverse().join("");
}
class Solution {
public String convertToTitle(int n) {
StringBuilder sb = new StringBuilder();
while (n > 0) {
n--;
sb.append((char) ('A' + n % 26));
n /= 26;
}
return sb.reverse().toString();
}
}
string convertToTitle(int n) {
string out;
while (n > 0) {
n--;
out += (char) ('A' + n % 26);
n /= 26;
}
reverse(out.begin(), out.end());
return out;
}
Explanation
This is the reverse of decoding a column label: we turn a number into Excel letters. It is almost like writing a number in base 26, but with one twist — there is no zero digit, so we subtract 1 at each step.
The loop peels off one letter at a time from the right. Normally n % 26 would give 0..25, but Excel uses A..Z = 1..26 with no zero. The fix is n -= 1 before each step, which shifts the range to 0..25 so that chr(ord('A') + n % 26) maps cleanly to a letter.
After grabbing the letter we do n //= 26 to move to the next place. Because we build letters from least significant to most significant, we reverse the collected characters at the end.
Example: n = 701. Step 1: 701 - 1 = 700, 700 % 26 = 24 which is 'Y', then 700 // 26 = 26. Step 2: 26 - 1 = 25, 25 % 26 = 25 which is 'Z', then 25 // 26 = 0. Reversing 'Y','Z' gives "ZY".
Each pass divides n by 26, so the loop runs only a handful of times.