Last Updated: 17 Mar, 2021

Concatenate The Largest Digit

Easy
Asked in companies
OlaSalesforceCGI

Problem statement

You are given three non-zero numbers ‘A’, ‘B’, and ‘C’. The task is to find the number formed by concatenating the largest digit from each of these numbers in the order of ‘A’, ‘B’, and ‘C’.

For Example :
A = 5678, B = 45 and C = 769
The largest digit in ‘A’ is ‘8’, ‘B’ is ‘5’, and ‘C’ is ‘9’. The new number formed by concatenating the largest digit from each of these numbers is ‘859’. So, the answer is ‘859’.
Input Format :
The first line of input contains an integer ‘T’ which denotes the number of test cases. Then, the ‘T’ test cases follow.

The first and only line of each test case contains three space-separated numbers, ‘A’, ‘B’, and ‘C’, denoting the given numbers.
Output Format :
For every test case, return the number formed by concatenating the largest digit from ‘A’, ‘B’, and ‘C’.
Note :
You do not need to print anything; it has already been taken care of. Just implement the function.
Constraints :
1 <= T <= 10^4
1 <= A, B, C <= 10^6

Time limit: 1 Sec

Approaches

01 Approach

A simple and efficient approach is to find all the digits of the given number and find the largest digit from them. For a number ‘x’, the digit at units place is equal to ‘x%10’ (‘%’ gives the division’s remainder). If we divide ‘x’ by ‘10’, each digit of ‘x’ will be shifted to the right, and the digit at the hundreds place will be shifted to units place. Now ‘x%10’ will give the digit at the hundreds place in the original ‘x’. So, keep dividing ‘x’ by ‘10’ until ‘x’ becomes ‘0’ to find all the digits of ‘x’. 

The ‘largestDigit(integer x)’ function. Used to find the largest digit in ‘x’:

  • Initialize integer ‘res = 0’. Use it to find the largest digit in ‘x’.
  • Run a loop until ‘x’ is not equal to ‘0’:
    • If ‘x%10’ is greater than ‘res’, then:
      • ‘res = x’.
    • ‘x = x/10’. To shift all digits of ‘x’ to the right.
  • Return ‘res’.

Similarly, to concatenate a digit to ‘x’, multiply ‘x’ by ‘10’ and add the digit to the new value of ‘x’. Use ‘largestDigit’ to find the largest digit in ‘A’, ‘B’, ‘C’ and concatenate it to ‘res’.

  • Initialize integer ‘res’. Use it to store the answer.
  • ‘res = largestDigit(A)’. Store the largest digit of ‘A’ in ‘res’.
  • ‘res = (res*10) + largestDigit(B)’. Concatenate the largest digit in ‘B’ to ‘res’.
  • ‘res = (res*10) + largestDigit(C)’. Concatenate the largest digit in ‘C’ to ‘res’.
  • Return ‘res’ as the answer.