# Produce a number such that the digits of the number should be maximum of the digits of the numbers in a given array

I have a method that should produce a number such that the digits of the number should be maximum of the digits of the numbers in a given array. For example if the given array is {32,145,1064}, the units maximum is 5, tens maximum is 6, hundreds maximum is 1,etc. So the number produced should be 1165. Similarly {638,245,2482} should produce 2688. I have done the following but that updates only the unit digit.

``````public void produceNumber(int[] arr)
{
int num = arr;
for(int i=1;i<arr.length;i++)
{
int temp = num;
while(arr[i] > 0)
{
if(arr[i] % 10 > temp % 10)
num = (num/10)*10 + arr[i]%10;//Line 10
arr[i] /= 10;
temp /= 10;
}
}
System.out.println(num);
}
``````

Something is going wrong in line 10. Please suggest a way to do this.

## 1 answer

• answered 2018-10-11 19:31

Your idea is close but not quite right. You can do something like the following to achieve the wanted outcome:

``````int produceNumber(int [] arr)
{

int [] amx = new int;
int mx = 0;
for(int i=0;i<arr.length;i++)
{
int idx = 0;
while(arr[i] > 0)
{
amx[idx] = Math.max(amx[idx], arr[i] % 10);
arr[i] /= 10;
idx++;
mx = Math.max(mx, idx);
}
}

//now build the number
int res = 0, factor = 1;
for(int i=0; i<mx;i++){
res += amx[i] * factor;
factor *= 10;
}

return res;
}
``````

In the sample I limited the size of the array to 10, so I assume that the maximum number is at most 10 digits long, but you can change it if you like.

PS: You may need to do small corrections somewhere since I wrote it directly in C++ and only afterwards I noticed it was tagged java.