Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Created November 11, 2013 16:54
Show Gist options
  • Select an option

  • Save rfaisal/7416414 to your computer and use it in GitHub Desktop.

Select an option

Save rfaisal/7416414 to your computer and use it in GitHub Desktop.
public class MoveZerosToEnd {
public static int[] move(int[] arr){
int current=0;
for(int i=0;i<arr.length;i++){
if(arr[i]!=0)
arr[current++]=arr[i];
}
while(current<arr.length)
arr[current++]=0;
return arr;
}
}
public class MoveZerosToEndTest {
@Test
public void testMove() {
assertArrayEquals(new int[]{}, MoveZerosToEnd.move(new int[]{}));
assertArrayEquals(new int[]{0}, MoveZerosToEnd.move(new int[]{0}));
assertArrayEquals(new int[]{1}, MoveZerosToEnd.move(new int[]{1}));
assertArrayEquals(new int[]{1,2,3,4}, MoveZerosToEnd.move(new int[]{1,2,3,4}));
assertArrayEquals(new int[]{1,2,3,0}, MoveZerosToEnd.move(new int[]{1,2,3,0}));
assertArrayEquals(new int[]{1,3,2,0}, MoveZerosToEnd.move(new int[]{1,0,3,2}));
assertArrayEquals(new int[]{1,2,0,0}, MoveZerosToEnd.move(new int[]{1,0,0,2}));
assertArrayEquals(new int[]{1,0,0,0}, MoveZerosToEnd.move(new int[]{0,0,0,1}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment