Saturday, November 9, 2013

Numbers to Letters.

Difficulty: (1/5).

By numbering the letters of the alphabet from a=1 to z=26, and letting space=0, we can encode a multi-word message M of length k using the equation:
encode(M) = M[0]*27^(k-1) + M[1]*27^(k-2) + ... + M[k-2]*27^1 + M[k-1]*27^0
where M[i] is the value of character i of the message, and ^ means exponentiation.
For example, the code number for "ab cd" is
encode("ab cd") = 1*27^4 + 2*27^3 + 0*27^2 + 3*27^1 + 4*27^0 = 570892
Write a program that will take a number on the command line and decode it into a string in the manner just described. For example, given the input:
% java NumbersToLetters 570892
the program should print out the string "ab cd". Hints: use modular arithmetic. Use a long to store the number, since an int will only hold a message 6 characters long.

To test your program, decode the number 42120723190451.

CS1 Deadline: 11/29/2013
Use: handin cs1113 extra4

Optional: If you store the code number as an int, your program will only be able to handle messages of 5 letters or less. Using a long increases the maximum message size to 11, but this is still pretty short. Extend your program to larger messages by using BigInteger or another multiprecision library to store the code number. Test your enhanced program by decoding the number:

No comments:

Post a Comment