Check the Equality
National Olympiad — National round (2013 season)
Submission name: equ.cpp
Problem summary
An equality contains one operation (+,−,*) and arbitrary lowercase letters mixed into the numbers. Remove the letters to recover the operands and claimed result. Check the equality.
Input
One line of digits, lowercase letters and the symbols +,−,*,=, without spaces.
Output
If correct, print Yes and the absolute difference of the two operands. If incorrect, print No and the correct operation result.
Constraints
0 ≤ numbers ≤ 1,000,000,000; 5 ≤ line length ≤ 100; for subtraction the first operand exceeds the second.
Worked example
An independently prepared example for this explanation.
Input
as4da5fd+xx2x3xx8xx=qw283
Output
Yes 193
Solution analysis
- Ignore lowercase letters. Build each number digit by digit; an operation ends the first operand and = ends the second.
- Evaluate the recovered operation in long long. If it matches the claimed result, output the absolute operand difference; otherwise output the computed result.
- The sample becomes 45+238=283. It is true, so output Yes and 238−45=193, rather than the result 283.
Why it works
Discarding letters leaves the decimal digits of each original number in order. The delimiter scan separates exactly the two operands and claimed result. Evaluation and comparison establish truth, and the chosen output follows the corresponding rule.
Watch out. On a true equality the requested number is the operand difference. Multiplication may reach 10^18.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
string text;
cin >> text;
long long numbers[3] = {};
int index = 0;
char operation = '+';
for (char symbol : text) {
// Letters are ignored; delimiters alone select the next number.
if (symbol >= '0' && symbol <= '9') {
numbers[index] = numbers[index] * 10 + symbol - '0';
} else if (symbol == '+' || symbol == '-' || symbol == '*') {
operation = symbol;
index = 1;
} else if (symbol == '=') {
index = 2;
}
}
long long result;
if (operation == '+') {
result = numbers[0] + numbers[1];
} else if (operation == '-') {
result = numbers[0] - numbers[1];
} else {
result = numbers[0] * numbers[1];
}
if (result == numbers[2]) {
cout << "Yes " << max(numbers[0], numbers[1]) - min(numbers[0], numbers[1]);
} else {
cout << "No " << result;
}
cout << '\n';
}