Series Algorithm

A, B, C, .... Z, AA, AB, .... AZ, BA, BB, .... ZZ, AAA, .... Write a function that takes an integer n and returns string representation. Can someone tell me an algorithm to find the nth value in a series?

+4
source share
3 answers

Treat these lines as numbers in base 26 with A=0 . This is not an exact translation, because in a real database 26 A=AA=AAA=0 , so you need to make the necessary adjustments.

Here's the 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 needed.

+4
source

Without giving too much (since this question seems to be a home problem), what you are doing is close to the same as translating an integer n to base 26. Good luck!

+3
source

If, as others suspect, this is homework, then this answer probably will not help. However, if this is for a real project, it might make sense to create a generator instead, which is an easy and idiomatic task in some languages ​​such as Python. Something like that:

 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) 

Instead of giving the pattern itself, you can undo it and display from 0 to A, from 1 to B, etc., then enter a line. I ran the code above and it seems to work, but I have not tested it at all.

Hope you find this readable enough for implementation, even if you don't know Python. (For Pythonistas there, yes, the "for i in range (...)" loop is ugly and fearless, but from my point of view, I don’t know another way to do what I do here)

0
source

Source: https://habr.com/ru/post/1303305/


All Articles