Maximum number formed from the digits of given three numbers
Given 3 four-digit integers A, B, and C, the task is to print the number formed by taking the maximum digit from all the digits at the same positions in the given numbers.
Input: A = 3521, B = 2452, C = 1352
- The maximum of the digits that are at 1th place is equal to max(A = 1, B = 2, C = 2) 2.
- The maximum of the digits that are at 10th place is equal to max(A = 2, B = 5, C = 5) 5.
- The maximum of the digits that are at 100th place is equal to max(A = 5, B = 4, C = 3) 5.
- The maximum of the digits that are at 1000th place is equal to max(A = 3, B = 3, C = 1) 3.
Therefore, the number formed is 3552.
Input: A = 11, B = 12, C = 22
Approach: The problem can be solved by iterating over the digits of the given integers. Follow the steps below to solve the problem:
- Initialize a variable, say ans as 0 and P as 1 to store the maximum number possible and the position value of a digit.
- Iterate until A, B and C are greater than 0 and perform the following steps:
- Find the digits at the unit places of the numbers A, B, and C and store them in variables say a, b and c respectively.
- Update A to A/10, B to B/10, and C to C/10.
- Increment ans by the P*max(a, b, c) and then update P to P*10.
- Finally, after completing the above steps, print the answer stored in ans.
Below is the implementation of the above approach:
Time Complexity: O(log(N))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.