Roy McAvoy
Roy McAvoy

Reputation: 21

Number to text decoding

Can anybody help me come up with an algorithm or way to decode a number to 3 characters when they are encoded in the following manner:

Each element represents 3 alphabetic characters as in the following examples:

DOG -> (3 * 26^2) + (14 * 26) + 6 = 2398

CAT -> (2 * 26^2) + (0 * 26) + 19 = 1371

ZZZ -> (25 * 26^2) + (25 * 26) + 25 = 17575

So say I have 7446 or 3290 how would I go about converting them to text?

Upvotes: 2

Views: 2526

Answers (2)

Novikov
Novikov

Reputation: 4489

Modulo

input = 2398
iteration = 1
while input > 0
    character = input % 26
    input = input - character
    input = input / 26
    print character

Upvotes: 0

Mark Byers
Mark Byers

Reputation: 838974

Try this to extract the letters in reverse order:

7446             % 26 = 10
(7446 / 26)      % 26 = 0
(7446 / 26 / 26) % 26 = 11

For example:

1371             % 26 = 19 (T)
(1371 / 26)      % 26 = 0  (A)
(1371 / 26 / 26) % 26 = 2  (C)

CAT

The % refers to the modulo operation. x % y gives you the remainder of the division x / y.

Upvotes: 3

Related Questions