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
- 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.
- ABC already works when A = C. Otherwise ABBA has the required prefix exactly when B = C. If neither condition holds, ABCBA always works.
- 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.
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';
}