0 = A
1 = B
...
25 = Z
26 = AA
27 = AB
...
701 = ZZ
702 = AAA
I cannot think of any solution that does not involve loop-bruteforce :-(
I expect a function/program, that accepts a decimal number and returns a string as a result.
0 = A
1 = B
...
25 = Z
26 = AA
27 = AB
...
701 = ZZ
702 = AAA
I cannot think of any solution that does not involve loop-bruteforce :-(
I expect a function/program, that accepts a decimal number and returns a string as a result.
Python, 44 chars
Oh c'mon, we can do better than lengths of 100+ :
Testing:
If you look carefully the excel representation is like base 26 number but not exactly same as base 26.
In Excel conversion
Z + 1 = AA
while in base-26Z + 1 = BA
The algorithm is almost same as decimal to base-26 conversion with just once change. In base-26, we do a recursive call by passing it the
quotient
, but here we pass itquotient-1
:Java Implementation
F# :
166137Since I am not sure what base you're converting from and what base you want (your title suggests one and your question the opposite), I'll cover both.
Algorithm for converting
ZZ
to701
First recognize that we have a number encoded in base 26, where the "digits" are
A..Z
. Set a countera
to zero and start reading the number at the rightmost (least significant digit). Progressing from right to left, read each number and convert its "digit" to a decimal number. Multiply this by 26a
and add this to the result. Incrementa
and process the next digit.Algorithm for converting
701
toZZ
We simply factor the number into powers of 26, much like we do when converting to binary. Simply take
num%26
, convert it toA..Z
"digits" and append to the converted number (assuming it's a string), then integer-divide your number. Repeat untilnum
is zero. After this, reverse the converted number string to have the most significant bit first.Edit: As you point out, once two-digit numbers are reached we actually have base 27 for all non-least-significant bits. Simply apply the same algorithms here, incrementing any "constants" by one. Should work, but I haven't tried it myself.
Re-edit: For the
ZZ->701
case, don't increment the base exponent. Do however keep in mind thatA
no longer is 0 (but 1) and so forth.Explanation of why this is not a base 26 conversion
Let's start by looking at the real base 26 positional system. (Rather, look as base 4 since it's less numbers). The following is true (assuming A = 0):
And so forth... notice that
AA
is 0 rather than 4 as it would be in Excel notation. Hence, Excel notation is not base 26.Scala: 63 chars
Prolog,
109123 bytesConvert from decimal number to Excel string:
That code does not work for c(27, N), which yields N='BB'
This one works fine:
Tests:
Converts from Excel string to decimal number (87 bytes):