How would you translate a vanity phone number like
1 800 RED CROSS to its actual phone number:
If you're dialing the number on a phone ☎️, you just find the letters on the keypad and press the corresponding numbers. However, writing a program to translate a vanity number requires an algorithm.
The input data to this algorithm is a vanity phone number. It can take many forms:
1 800 RED CROSS 1-800-RED-CROSS 1-800-Red-Cross 1800REDCROS 1.800.RED.CROS 800-RED-cross 800REDCROS
With the data in mind, let's make some basic assumptions about the algorithm:
- The input data is a string.
- The string must be at least 10 characters long, which is a 10-digit number without separators.
- The string may include all valid characters.
There are many different ways to write this algorithm. But the basic approach is:
- Accept a vanity phone number as an input string.
- If the string length is less than 10, output an error message and quit the program.
- Convert the string to be all uppercase.
- For each character in the string:
- If the character is in the range
Z, translate it to its corresponding keypad number and output the number.
- If the character is not in the range
Z, output the character.
Here are some tips for implementing this algorithm in Java ☕️:
toUpperCase()function returns an uppercase version of a string.
charAt()function accesses a specific character in a string.
forloop can work nicely with
charAt()to access each character of the string, in order.
- One way to translate a letter from
Zto its corresponding keypad number is to use a
switchstatement, where each case is a letter from
There are many ways to implement an algorithm to translate vanity phone numbers to real phone numbers. The first step is to develop the algorithm itself. Consider the input data, assumptions, processing logic, and output. Developing the algorithm first makes coding the solution easier.
Now it’s your turn. Can you code the solution? 👩💻🧑💻
Thanks for reading.
Follow me on Twitter
@realEdwinTorres for more programming tips. 😀