Practice › Strings
Excel Column Title
Easy · Strings · Asked at Microsoft, Amazon, Zoho
Spreadsheet columns are named A, B, …, Z, AA, AB, …, AZ, BA, …, ZZ, AAA, … Print the name of column number n.
Input
A single integer n.
Output
The column title in capital letters.
Constraints
- 1 ≤ n ≤ 2^31 − 1
It is base 26 with digits 1…26 instead of 0…25: take (n − 1) % 26 as the letter, then set n = (n − 1) / 26.
Example 1
Input
28
Output
AB
Example 2
Input
701
Output
ZY
Hints
- It looks like base 26, but there is no zero digit: Z is 26, not 0.
- Subtract 1 before taking the remainder, so 1…26 maps to A…Z.
Approach
Repeat while n > 0: decrease n by one, the letter is 'A' + n % 26, then n = n / 26. The letters come out from the last to the first, so build the string backwards (or reverse it at the end). Without the "minus one", 26 would wrongly become "A@" instead of "Z".
Complexity: O(log₂₆ n) time · O(1) space
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n;
cin >> n;
string t;
while (n > 0) {
n--;
t += char('A' + n % 26);
n /= 26;
}
reverse(t.begin(), t.end());
cout << t << "\n";
return 0;
}Python solution
n = int(input())
t = []
while n > 0:
n -= 1
t.append(chr(ord("A") + n % 26))
n //= 26
print("".join(reversed(t)))Java solution
import java.util.*;
public class Main {
public static void main(String[] args) {
long n = new Scanner(System.in).nextLong();
StringBuilder t = new StringBuilder();
while (n > 0) {
n--;
t.append((char) ('A' + n % 26));
n /= 26;
}
System.out.println(t.reverse());
}
}