Maximum Digit
Autumn Tournament (2009)
Submission name: maxdigit.cpp
Problem summary
Given three three-digit positive integers B, C, D and a position K counted from the left, find the largest of their K-th digits that satisfies 9 + (A − 5) > 8. Print No if none does.
Input
B, C, D, K on one line.
Output
The largest eligible digit, or No.
Constraints
100 ≤ B, C, D ≤ 999; 1 ≤ K ≤ 3.
Worked example
Original statement sample.
Input
235 567 123 3
Output
7
Solution analysis
- The inequality simplifies to A + 4 > 8, or A > 4. Thus only digits 5 through 9 qualify.
- Use divisor 100, 10, or 1 for K equal to 1, 2, or 3. The selected digit is (number/divisor)%10. Find the maximum of the three selected digits and test it against 4.
- For 235, 567, 123 at position 3, the selected digits are 5, 7, 3. Their maximum 7 satisfies the inequality.
Why it works
The divisor formula extracts the requested position from every number. If the maximum exceeds 4 it is eligible and at least as large as every other candidate. If it does not, no candidate exceeds 4, so none satisfies the inequality.
Watch out. Positions are counted from the left. The inequality is strict: digit 4 is ineligible.
Commented C++17 solution
An independently written complete program with standard headers.
// Key idea: The divisor formula extracts the requested position from every number. If the maximum
// exceeds 4 it is eligible and at least as large as every other candidate.
#include<algorithm>
#include<iostream>
#include<limits>
#include<string>
using namespace std;
int main(){
ios::sync_with_stdio(false);
cin.tie(nullptr);
int b,c,d,position;
cin>>b>>c>>d>>position;
int divisor=1;
for(int step=position;step<3;step++){
divisor*=10;
}
int largest=max({(b/divisor)%10,(c/divisor)%10,(d/divisor)%10});
if(largest>4){
cout<<largest<<'\n';
}
else{
cout<<"No\n";
}
}