Lucky Ticket
National Olympiad — Municipal round (2012 season)
Submission name: lucky.cpp
Problem summary
A six-digit ticket is lucky if the first three digits and last three digits have equal sums, and the second digit is at least the fourth. Report the sum if lucky, otherwise the specified failure code.
Input
One six-digit serial number.
Output
The first-half sum if both conditions hold; 30 if both fail; 31 if only the sum condition fails; 32 if only the digit comparison fails.
Constraints
The input is a six-digit number.
Worked example
An independently prepared example for this explanation.
Input
273516
Output
12
Solution analysis
- Read the number as a string so each digit has a direct position. Compute the two sums.
- Store each condition as a boolean. Four combinations map directly to the required answer or failure code.
- For 273516, the sums are 12 and 12, and 7 ≥ 5. Both tests pass, so print 12.
Why it works
The two computed booleans are exactly the ticket conditions. The four branches exhaust their truth combinations and output the prescribed value in each case.
Watch out. The second and fourth digits have indices 1 and 3. Equality is allowed in the comparison.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
using namespace std;
int main() {
string ticket;
cin >> ticket;
int left = ticket[0] + ticket[1] + ticket[2] - 3 * '0';
int right = ticket[3] + ticket[4] + ticket[5] - 3 * '0';
// Keep the two conditions separate to choose the failure code.
bool sumsMatch = left == right;
bool orderMatches = ticket[1] >= ticket[3];
if (sumsMatch && orderMatches) {
cout << left;
} else if (!sumsMatch && !orderMatches) {
cout << 30;
} else if (!sumsMatch) {
cout << 31;
} else {
cout << 32;
}
cout << '\n';
}