Translate a Telephone Word
National Olympiad — Municipal round (2011 season)
Submission name: telephone.cpp
Problem summary
Replace uppercase Latin letters in a telephone number by their standard telephone keypad digits, leaving existing digits and hyphens unchanged.
Input
One string containing uppercase Latin letters, digits and hyphens.
Output
The translated telephone string.
Constraints
String length 3–30.
Worked example
Input and output for the worked example discussed below.
Input
1-888-SHOP-IBM
Output
1-888-7467-426
Solution analysis
- Store the keypad digit for each of the 26 letters in alphabet order: ABC→2, DEF→3, GHI→4, JKL→5, MNO→6, PQRS→7, TUV→8, WXYZ→9.
- Scan the string. An uppercase letter indexes this table by letter−'A'; every other permitted character is already part of the telephone number and is preserved.
- SHOP becomes 7467 and IBM becomes 426, while the prefix 1-888- and separating hyphen do not change. Direct table lookup avoids a long chain of overlapping conditions.
Why it works
The table assigns exactly the specified keypad digit to each letter, and the scan changes only letters. Therefore every output position is precisely the required translation of its input position.
Watch out. PQRS and WXYZ each have four letters. Preserve all hyphens and numeric digits. The input is uppercase, so index from A rather than a.
Commented C++17 solution
An independently written complete program with standard headers.
#include<algorithm>
#include<array>
#include<cmath>
#include<iostream>
#include<limits>
#include<map>
#include<numeric>
#include<set>
#include<string>
#include<vector>
using namespace std;
int main(){
string number;
cin>>number;
const string keypad="22233344455566677778889999";
for(char&symbol:number){
// Only letters use the keypad table; separators stay unchanged.
if(symbol>='A'&&symbol<='Z'){
symbol=keypad[symbol-'A'];
}
}
cout<<number<<'\n';
}