The Totem’s Value
National Olympiad — Municipal round (2019 season)
Submission name: totem.cpp
Problem summary
A 3 by 3 grid contains decimal digits. Read the main diagonal from top-left to bottom-right as one three-digit numeral, and the other diagonal from top-right to bottom-left as another. Find their product; leading zeros are allowed in these numerals.
Input
Three lines, each containing three adjacent digits.
Output
The product of the two diagonal values.
Constraints
The input is exactly a 3 by 3 grid of decimal digits.
Worked example
An independently prepared example for this explanation.
Input
123 456 789
Output
56763
Solution analysis
- Read each row as a string, so leading zeros remain available at their grid positions. The main diagonal uses positions (0,0),(1,1),(2,2). The other uses (0,2),(1,1),(2,0).
- Build each numeral by multiplying the accumulated value by 10 and adding the next digit. Repeat for all three rows and multiply the resulting two integers.
- For the first sample, the diagonals form 159 and 357, and 159·357=56763. For the second, they form 001 and 201; their numeric values are 1 and 201, yielding 201.
Why it works
At each row, multiplying by ten shifts the preceding diagonal digits left by one place and adding the selected digit appends the next diagonal entry. After three rows the accumulators are exactly the required values, so their product is the desired result.
Watch out. The center digit belongs to both diagonals. Read rows as strings rather than integers that lose leading zeros.
Commented C++17 solution
An independently written complete program with standard headers.
#include <algorithm>
#include <array>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
using namespace std;
int main() {
int mainDiagonal = 0;
int otherDiagonal = 0;
for (int row = 0; row < 3; ++row) {
string digits;
cin >> digits;
// Appending a diagonal digit shifts the previous value one decimal place.
mainDiagonal = mainDiagonal * 10 + digits[row] - '0';
otherDiagonal = otherDiagonal * 10 + digits[2 - row] - '0';
}
cout << mainDiagonal * otherDiagonal << '\n';
}