In: Computer Science
Rattapoom is a boy that loves to play with numbers. He received digit cards as a present on his birthday, where he joyously showed it to his friends in the neighborhood. He received N cards of number, where each card contains a single digit. He wishes to arrange all his cards in such a way that the digits form a smallest possible N-digit number, and that N-digit number must not begin with 0.
Given N digit cards that Rattapoom received, arrange the digits to form an N-digit number that is the smallest possible and does not start with 0.
INPUT
The first line defines an integer N (2 ≤ N ≤ 1,000). The next line defines a sequence of N digits, separated by whitespace, representing each card of digit. Assume that there will be at least one digit that is not zero.
OUTPUT
A line holding an N-digit number that does not start with 0. All digits are displayed without any whitespaces in between them.
Sample Input |
Sample Output |
4 9 4 6 2 |
2469 |
6 3 0 8 1 3 3 |
103338 |
Write a Java program using methods to implement this case.
The N digits should be stored in an array of size N. After storing the digits in the array, function named minimum is called. Inside the function minimum the array is sorted in ascending order, after that the elements of the array are printed from first element to last element, if first element is 0 (zero) then second element is printed first and 0 is printed as second digit.
code:
import java.util.*;
public class Minimum_number
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int N = in.nextInt();
int[] arr = new int[N];
//entering the digits in an array
for(int i=0;i<N;i++)
arr[i]=in.nextInt();
//calling minimum method by reference
minimum(arr,N);
} // main method closed
static void minimum(int array[], int n)
{
//using bubble sort to sort the array.
for(int i=0;i<n-1;i++)
for(int j=0;j<n-i-1;j++)
{
//swapping consecutive elements if Nth element is greater than (N+1)th element
if(array[j]>array[j+1])
{
int t=array[j];
array[j]=array[j+1];
array[j+1]=t;
}
}
System.out.println();
//if first element is zero then print second element first and 0 as 2nd element
if(array[0]==0)
{
System.out.print(array[1]);
System.out.print(array[0]);
for(int i=2;i<n;i++)
System.out.print(array[i]);
}
else
{
// print the elements of array
for(int i=0;i<n;i++)
System.out.print(array[i]);
}
System.out.println();
}// minimum method closed
} // class closed
Output:
Please hit thumbs up if you like the answer.