從鍵盤讀入n個整數放入數組中,編寫函數CompactIntegers,刪除數組中所有值爲0的元素,其後元素向數組首端移動。
注意,CompactIntegers函數需要接受數組及其元素個數作爲參數,函數返回值應爲刪除操作執行後數組的新元素個數。輸出刪除後數組中元素的個數並依次輸出數組元素。
樣例輸入: (輸入格式說明:5爲輸入數據的個數,3 4 0 0 2 是以空格隔開的5個整數)
5
3 4 0 0 2
樣例輸出:(輸出格式說明:3爲非零數據的個數,3 4 2 是以空格隔開的3個非零整數)
3
3 4 2
樣例輸入:
7
0 0 7 0 0 9 0
樣例輸出:
2
7 9
樣例輸入:
3
0 0 0
樣例輸出:
0
import java.util.Scanner;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
for(int i=0;i<n;i++){
a[i]=sc.nextInt();
}
int t = 0;
int b[]=new int[n];
for(int i=0;i<a.length;i++){
if(a[i]!=0){
b[t++]=a[i];
}
}
System.out.println(t);
for(int i=0;i<t;i++){
System.out.print(b[i]+ " ");
}
}
}