开发者

convert number to combination of letters

I need to convert a number between 1 and 6000000 to a letter combination like ABCDE. Less letters is better. but i'm guessing i will need 4 or 5.

Can someone point me in the right direction as how to write an algorithm to convert numbers to lett开发者_C百科ers and back? only A-Z. (caps).


You need to convert to base-26 numbering: 0 is A, 1 is B, 25 is Z, 26 is BA, etc.

The Hexavigesimal Wikipedia article has code for conversion to base 26.


There are 26 letters in the alphabet.

TYou have 26^4 < 6 000 000 and 26^5 > 6 000 000

Then you will need 5 letters, for most of your elements

Now you just need to express your number in base 26.

Their is only one way to write an X in 0 ... 6 000 000 as follow:

X = a4*26^4 + a3*26^3+ a2*26^2+ a1*26^1+a0

ai in {0,...25} then you just map ai with a letter from A to Z


The most naive thing to do would be to let A,B,...,Z represent the numbers 0,1,...,25 and the just convert your number to base 26 to get the alphabetic conversion.

For example, there is a C# implementation in this answer to this post.


Well if you want to convert from the decimal representation, then there are 10 digits [0-9] and if you want to have one character per decimal digit in the result, then you will need ten alpha characters. But if you convert from the binary representaion, just replace every 0 with an 'A' and every 1 with a 'B'...

everything depends on how you want to do it... The base you decide to use will determine how many letters you will need.

as an example, to do it from a binary representation, take the number mod 2. If the result is 0 add an 'A' if its a 1, add a 'B' Divide the number by 2 (or rightshift it one position.) repeat until number is zero.

  start with value of  57  
 1.  57 Mod 2 = 1    A
 2.  57 / 2 = 28
 3.  28  Mod 2 = 0   BA
 4.  28 / 2 = 14
 5.  14 mod 2 = 0    BBA
 6.  14 / 2 = 7
 7.   7 mod 2 = 1    ABBA   --- A musical group !
 8.   7 / 2 = 3
 9.   3 mod 2 = 1    AABBA
10.   3/ 2 = 1
11.   1 mod 2 = 1    AAABBA
12.   1 / 2 = 0    --- -done  


You should equate A = 0, B = 1 and so on upto Z = 25.

This would become a number system with the base (or radix) 26.

With this in mind, two digits can represent numbers ranging from 0 - 675 (ZZ = 675). 3 Digits would represent 26^3. i.e 0 - 17575.

With 5 digits you can represent from 0 - 11881375 (ZZZZZ).

You can take any standard algorithm that converts between decimal to its own radix to do that. Conversion between Number bases can be referenced for help.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜