A, B, C,…. Z, AA, AB, ….AZ, BA,BB,…. , ZZ,AAA, …., write a function that takes a integer n and returns the string presentation. Can somebody tell me the algorithm to find the nth value in the series?
-
11If this is homework, it would be nice for you to include it in your tags. – Anthony Forloney Mar 06 '10 at 00:15
-
Does n start a 1 or does n start at 0 ? – John Knoeller Mar 06 '10 at 00:42
-
This has been asked at least 3 times here, each time with a flurry of implementations in the answer. – Svante Mar 06 '10 at 11:06
-
This is the opposite question... http://stackoverflow.com/questions/763691/programming-riddle-how-might-you-translate-an-excel-column-name-to-a-number – Sparr Mar 08 '10 at 03:09
3 Answers
Treat those strings as numbers in base 26 with A=0
. It's not quite an exact translation because in real base 26 A=AA=AAA=0
, so you have to make some adjustments as necessary.
Here's a Java implementation:
static String convert(int n) {
int digits = 1;
for (int j = 26; j <= n; j *= 26) {
digits++;
n -= j;
}
String s = "";
for (; digits --> 0 ;) {
s = (char) ('A' + (n % 26)) + s;
n /= 26;
}
return s;
}
This converts 0=A, 26=AA, 702=AAA
as required.

- 376,812
- 128
- 561
- 623
Without giving away too much (since this question seems to be a homework problem), what you're doing is close to the same as translating that integer n
into base 26. Good luck!

- 219,201
- 40
- 422
- 469
-
-
@polygenelubricants, it's close enough for homework. Giving a complete solution (like yours) is a disservice to learner. – Carl Norum Mar 06 '10 at 02:04
-
1It may or may not be homework, we can never be 100% sure. I prefer not to deal with meta issues and just answer the questions the best I can. I understand your point of view, though. "Homework-y" questions used to bother me too. – polygenelubricants Mar 06 '10 at 02:10
If, as others suspect, this is homework, then this answer probably won't be much help. If this is for a real-world project though, it might make sense to do make a generator instead, which is an easy and idiomatic thing to do in some languages, such as Python. Something like this:
def letterPattern():
pattern = [0]
while True:
yield pattern
pattern[0] += 1
# iterate through all numbers in the list *except* the last one
for i in range(0,len(pattern)-1):
if pattern[i] == 26:
pattern[i] = 0
pattern[i+1] += 1
# now if the last number is 26, set it to zero, and append another zero to the end
if pattern[-1] == 26:
pattern[-1] = 0
pattern.append(0)
Except instead of yielding pattern
itself you would reverse it, and map 0 to A, 1 to B, etc. then yield the string. I've run the code above and it seems to work, but I haven't tested it extensively at all.
I hope you'll find this readable enough to implement, even if you don't know Python. (For the Pythonistas out there, yes the "for i in range(...)" loop is ugly and unpythonic, but off the top of my head, I don't know any other way to do what I'm doing here)

- 21,762
- 11
- 61
- 90