131k views
9 votes
Write a method that returns a version of the given array where all the 10's have been removed. The remaining elements should shift left towards the start of the array as needed, and the empty spaces at the end of the array should be set to 0.

Ex: {1, 10, 10, 2} yields {1, 2, 0, 0}. You may modify and return the given array or make a new array.

Code:

public class RemoveTen {
public static void main(String[] args) {
int[] nums = {1, 10, 10, 2};
int[] result = removeTen(nums);
for(int i = 0; i < result.length; i++)
System.out.print(result[i] + " ");
}

public static int[] removeTen(int[] nums) {
/*FIXME Complete the implementation of the removeTen method*/
}
}

User Yitzy
by
4.6k points

1 Answer

5 votes

Answer:

The removeTens method is as follows

public static int[] removeTen(int[] nums) {

int [] arr = nums;

int index = 0;

while(index < arr.length && arr[index] != 10){

index++;

for(int j = index + 1; j < arr.length; j++) {

if(arr[j] != 10) {

arr[index] = arr[j];

arr[j] = 10;

index++; } }

for( ; index < arr.length; index++){

arr[index] = 0;}}

return arr;

}

Step-by-step explanation:

This defines the removeTens method; it receives array nums as its parameter

public static int[] removeTen(int[] nums) {

This creates and initializes a new array

int [] arr = nums;

This initializes index to 0

int index = 0;

The following is repeated when array element is not 10 and if array index is still valid

while(index < arr.length && arr[index] != 10){

This increments the index by 1

index++;

This iterates through the array

for(int j = index + 1; j < arr.length; j++) {

This checks if array element is not 10

if(arr[j] != 10) {

If yes:

arr[index] = arr[j];

The current array element is set to 10

arr[j] = 10;

The index is incremented by 1

index++; } }

This iterates through the array again and move 0s to the back

for( ; index < arr.length; index++){

arr[index] = 0;}}

This returns the new array

return arr;

}

User Bhinks
by
4.4k points