Transform the Password
National Olympiad — Municipal round (2020 season)
Submission name: pass.cpp
Problem summary
A five-character old password contains a digit, three lowercase Latin letters, and another digit. Double each endpoint digit; if the doubled value has two digits, replace it by the sum of those digits. Sort the three letters alphabetically to form the new password.
Input
One five-character password without spaces.
Output
The transformed five-character password.
Constraints
Endpoint characters are digits; the three middle characters are lowercase Latin letters.
Worked example
An independently prepared example for this explanation.
Input
5sad3
Output
1ads6
Solution analysis
- The doubled endpoint digit is between 0 and 18. Its digit sum is doubled/10 + doubled%10, a single digit.
- Sort only positions 1 through 3 in zero-based indexing. The endpoint digits stay at their respective ends.
- For 5sad3, doubling 5 produces 10, whose digit sum is 1. Sorting sad gives ads, while doubling 3 gives 6. Concatenating these pieces produces 1ads6.
Why it works
The digit helper implements both the one-digit and two-digit doubling cases. Sorting exactly the three middle letters puts them in the required order and preserves their multiplicities. Joining the three transformed parts gives the specified password.
Watch out. A doubled 9 becomes 9, not 18. Preserve repeated letters and any zero digit.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int transformedDigit(char digit) {
int doubled = 2 * (digit - '0');
return doubled / 10 + doubled % 10;
}
int main() {
string password;
cin >> password;
// The half-open range contains exactly the three middle letters.
sort(password.begin() + 1, password.begin() + 4);
cout << transformedDigit(password[0]);
cout << password.substr(1, 3);
cout << transformedDigit(password[4]) << '\n';
}