Pattern – Integer to Alphabets
Convert a given integer to its corresponding alphabetic representation where 1=A, 2=B, ..., 26=Z, 27=AA, 28=AB, etc.
Understand the Problem
Problem Statement
Given a number N, convert the number to character values based on alphabet positions. The mapping follows a pattern where 1 maps to 'A', 2 to 'B', ..., 26 to 'Z', 27 to 'AA', 28 to 'AB', and so on. This is similar to how Excel column labels are generated.
Constraints
- 1 ≤ N ≤ 10,000,000
- N is a positive integer
- Output should be uppercase alphabetic characters only
Examples
10J10 maps directly to the 10th letter of the alphabet, which is 'J'.
28AB28 = 26 + 2, so it maps to the 2nd letter 'B' with one complete cycle of 26, giving us 'AB' (where A represents one complete cycle of 26).
Solution
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
long long n;
scanf("%lld", &n);
char result[100];
int index = 0;
if (n <= 26) {
printf("%c", 'A' + n - 1);
return 0;
}
while (n > 26) {
int remainder = n % 26;
if (remainder == 0) {
result[index++] = 'Z';
n = n / 26 - 1;
} else {
result[index++] = 'A' + remainder - 1;
n = n / 26;
}
}
result[index++] = 'A' + n - 1;
for (int i = index - 1; i >= 0; i--) {
printf("%c", result[i]);
}
return 0;
}The C solution follows the same algorithmic approach. We use a character array to store the result characters. The key insight is handling the case when n % 26 equals 0 - this represents a 'Z' in the current position, and we need to reduce the quotient by 1 to account for the fact that we don't have a zero in our alphabet system. After building the string from right to left, we print it in reverse order.