cppAcademy
FROM LEARNING TO COMPETING

Intermediate.
Put your skills to the test.

Bulgarian Informatics Group D · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group D also includes challenging national-level problems. The six 2017 National tasks shared by Groups C and D use their existing permanent URLs. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP D2011 · EasyString conversion

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

  1. 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.
  2. 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.
  3. 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.

Complexity: O(L) time and O(1) auxiliary space besides the input/output string; the mapping table has constant length.

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';
}

Source: Arena Olimpiici ↗