Untitled
Anonymous
Plain Text
09/04/2025 3:57 PM
1.4 KB
14
Indexable
Never
package ARRAYS;
import java.util.Arrays;
import java.util.Scanner;
public class ZerosAtEnd {
/**
*This class takes an integer array nums and moves all the 0's to the end of the array. The relative order of the other elements must remain the same.
*
* Examples:
* Input: nums = [0, 1, 4, 0, 5, 2]
* Output: [1, 4, 5, 2, 0, 0]
* Explanation: Both the zeroes are moved to the end and the order of the other elements stay the same
*
* Input: nums = [0, 0, 0, 1, 3, -2]
* Output: [1, 3, -2, 0, 0, 0]
* Explanation: All 3 zeroes are moved to the end and the order of the other elements stay the same
*/
public static int [] movingZerosAtEnd(int nums[]){
int index = 0;
int zerosAtEnd[] = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
zerosAtEnd[index] = nums[i];
index++;
}
}
return zerosAtEnd;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("ARRAY SIZE -> " );
int size = sc.nextInt();
System.out.println("ENTER ARRAY ELEMENTS -> ");
int nums[] = new int[size];
for(int i = 0; i < size; i++) {
nums[i] = sc.nextInt();
}
System.out.println("AFTER MOVING ZEROS -> " + Arrays.toString(movingZerosAtEnd(nums)));
}
}
Editor is loading...
Leave a Comment