Confusing Threes and Eights
National Olympiad — Municipal round (2020 season)
Submission name: wsum.cpp
Problem summary
Given A and B, find the minimum sum after replacing every digit 8 by 3, and the maximum sum after replacing every digit 3 by 8.
Input
Two natural numbers A and B.
Output
The minimum and maximum sums, separated by a space.
Constraints
1 ≤ A,B < 100,000.
Worked example
An independently prepared example for this explanation.
Input
128 33
Output
156 216
Solution analysis
- Read each number as a string. Rebuild two integers from left to right, multiplying the current value by ten before appending each digit.
- For the minimum version, change only 8 to 3. For the maximum version, change only 3 to 8. Add the two minimum versions and the two maximum versions independently.
- For 128 and 33, the smaller versions are 123 and 33, giving 156. The larger versions are 128 and 88, giving 216. Digits other than 3 and 8 remain unchanged.
Why it works
Changing a digit 8 to 3 decreases its place-value contribution and affects no other digit; changing 3 to 8 increases it. Applying every allowed beneficial replacement independently gives the two required extreme sums.
Watch out. Do not replace 3 by 8 during the minimum calculation. Compute the two conversions from the original input.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
using namespace std;
int convert(const string& digits, char from, char to) {
int value = 0;
for (char digit : digits) {
if (digit == from) {
digit = to;
}
// Append the transformed digit at its decimal place.
value = value * 10 + digit - '0';
}
return value;
}
int main() {
string a, b;
cin >> a >> b;
int minimum = convert(a, '8', '3') + convert(b, '8', '3');
int maximum = convert(a, '3', '8') + convert(b, '3', '8');
cout << minimum << ' ' << maximum << '\n';
}