Unity in Zeros
In this program you are given with an array with 0's as elements in between the non zero elements, now you have to sort the array in such way that non zero elements should not loose the sequence whereas zeros should be in the last.
Alternative Method.
Input:
5 ---Array size
1
2
0
3
0
Output:
1
2
3
0
0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class HackerRank { | |
public static int[] unityInZeros(int[] input1) | |
{ | |
int k=0; | |
int [] newArray=new int[input1.length]; | |
for(int i=0;i<input1.length;i++){ | |
if(input1[i]!=0){ | |
newArray[k]=input1[i]; | |
k++; | |
} | |
} | |
return newArray; | |
} | |
public static void main(String[] args) { | |
Scanner in = new Scanner(System.in); | |
int[] output = null; | |
int ip1_size = 0; | |
ip1_size = Integer.parseInt(in.nextLine().trim()); | |
int[] ip1 = new int[ip1_size]; | |
int ip1_item; | |
for(int ip1_i = 0; ip1_i < ip1_size; ip1_i++) { | |
ip1_item = Integer.parseInt(in.nextLine().trim()); | |
ip1[ip1_i] = ip1_item; | |
} | |
output = unityInZeros(ip1); | |
for(int output_i=0; output_i < output.length; output_i++) { | |
System.out.println(String.valueOf(output[output_i])); | |
} | |
in.close(); | |
} | |
} |
Alternative Method.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
public class UnityInZerosAlternativveMethod { | |
public static int[] unityInZeros(int[] input1) | |
{ | |
int [] output=new int [input1.length]; | |
int k=0; | |
for(int i=0;i<input1.length;i++){ | |
for(int j=0;j<input1.length-1;j++){ | |
if(input1[j]==0&&input1[j+1]!=0){ | |
int tmp=input1[j]; | |
input1[j]=input1[j+1]; | |
input1[j+1]=tmp; | |
} | |
} | |
output[k]=input1[i]; | |
k++; | |
} | |
return output; | |
} | |
public static void main(String [] args){ | |
Scanner in = new Scanner(System.in); | |
int[] output = null; | |
int ip1_size = 0; | |
ip1_size = Integer.parseInt(in.nextLine().trim()); | |
int[] ip1 = new int[ip1_size]; | |
int ip1_item; | |
for(int ip1_i = 0; ip1_i < ip1_size; ip1_i++) { | |
ip1_item = Integer.parseInt(in.nextLine().trim()); | |
ip1[ip1_i] = ip1_item; | |
} | |
output = unityInZeros(ip1); | |
for(int output_i=0; output_i < output.length; output_i++) { | |
System.out.println(String.valueOf(output[output_i])); | |
} | |
} | |
} |
5 ---Array size
1
2
0
3
0
Output:
1
2
3
0
0
Comments
Post a Comment