Dec

17

/*Write a program in Java to accept a number. Using the digits of this number create the largest possible number.
For example, if the sentence entered is: 311409 then the largest possible number using its digits will be 943110.
*/

— Thank you Tarushi, CMS Gomti Nagar, Lucknow for asked this questions

import java.util.*;
public class Prog1
{
public void main(int num){
int len=0; // variable to store the of the number of digits in the given number.
int temp=num; // variable hold the value of num temporarily
while(temp!=0) // Loop used to find the length of the number
{
temp=temp/10;
len++;
}
int i=0;
int arr[]=new int[len]; // int arr is defined with len find from above loop
while(num!=0) // loop used to store each digit from given number to arr
{
arr[i]=num%10;
num=num/10;
i++;
}
Arrays.sort(arr); // it will sort the digits stored in ascending order
for(i = len – 1; i >= 0; i–) // Loop used to form greatest number using digits stored in arr in ascending order therefore this loop starts from len-1 till 0
{
num = num * 10 + arr[i];
}
System.out.println(num); //printing the greatest number
}
}


Leave a Reply