cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2012 · EasyDigit patterns

Smallest Symmetric Number

Autumn Tournament (2012)

Submission name: sym.cpp

Problem summary

Given three initial digits A, B and C, form the smallest palindrome whose first three digits are exactly A, B and C. A palindrome reads identically in either direction.

Source clarification. The PDF has no explicit leading-zero rule. This solution uses the ordinary decimal-number convention that the first digit is nonzero.

Input

Three decimal digits A, B and C separated by spaces.

Output

The digits of the smallest suitable palindrome, with no spaces.

Constraints

The input consists of three digits. The statement does not give separate digit bounds; as the prefix of an ordinary number, A is nonzero.

Worked example

Original statement sample, translated without changing its numeric data.

Input

2 3 5

Output

23532

Solution analysis

  1. A shorter positive number is smaller than every longer positive number, so first try a three-digit palindrome, then a four-digit palindrome, then a five-digit one.
  2. ABC already works when A = C. Otherwise ABBA has the required prefix exactly when B = C. If neither condition holds, ABCBA always works.
  3. For 235 neither equality holds, so append 32 to get 23532. For 733, the four-digit answer is 7337; for 333 no extra digits are needed.

Why it works

No answer can have fewer than three digits because the prefix has length three. A three-digit palindrome exists precisely when A = C. If this fails, a four-digit palindrome with the prefix must be ABBA, possible precisely when B = C. Otherwise ABCBA is a valid five-digit answer, and its final digits are forced. Checking these lengths in order gives the smallest answer.

Complexity: O(1) time and O(1) extra space: the input has a fixed number of values.

Watch out. Test the three-digit case before the four-digit case. The middle digit of an odd-length palindrome is not duplicated.

Commented C++17 solution

An independently written complete program with standard headers.

#include<iostream>
using namespace std;
int main(){
    char a,b,c;
    cin>>a>>b>>c;
    cout<<a<<b<<c;
    if(a==c){
        // The prefix is already a palindrome.
    }
    else if(b==c){
        cout<<a;
    }
    else{
        cout<<b<<a;
    }
    cout<<'\n';
}

Source: Arena Olimpiici ↗