Scrooge’s Safe Code
National Olympiad — Municipal round (2009 season)
Submission name: kod.cpp
Problem summary
From a positive six-digit number, form a code. Its first printed digit is the count of odd digits. Keep the digits in positions 1, 3, and 5 from the left, form a three-digit value and its reversal, then append their absolute difference without zero padding.
Source clarification. The PDF leaves the position origin and subtraction sign unclear. The official INFOS author solution and archived tests select positions 1, 3, 5 from the left, use the absolute difference, and print the two components consecutively without padding.
Input
A positive six-digit integer.
Output
The odd-digit count immediately followed by the absolute difference.
Constraints
100,000 ≤ N ≤ 999,999.
Worked example
An independently prepared example for this explanation.
Input
123456
Output
3396
Solution analysis
- Read the number as a six-character string, so each position is explicit. Count characters whose digit value is odd.
- The retained digits are at zero-based indices 0, 2, and 4. If these are a, c, e, their two values are 100a + 10c + e and 100e + 10c + a. Take their absolute difference.
- For 123456 there are three odd digits. The retained number is 135, its reversal is 531, and their absolute difference is 396. Concatenating 3 and 396 gives 3396.
Why it works
The loop counts each odd digit once. The two place-value expressions are exactly the retained digits in forward and reverse order. Printing their absolute difference after the count therefore constructs the required code.
Watch out. Count positions from the left and take an absolute difference. Print the two parts consecutively; a zero count is still printed, as in the official archived test producing 00.
Commented C++17 solution
An independently written complete program with standard headers.
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
string number;
cin >> number;
int odd = 0;
for (char character : number) {
if ((character - '0') % 2 == 1) {
odd++;
}
}
int first = number[0] - '0';
int middle = number[2] - '0';
int last = number[4] - '0';
// Positions 1, 3, 5 are counted from the left.
int forward = 100 * first + 10 * middle + last;
int backward = 100 * last + 10 * middle + first;
cout << odd << abs(forward - backward) << '\n';
}