谁能给出这道题更好的解法,以及用C++怎么实现?
这道Java题用C++怎么实现啊?我这么写好不? 谁能给个更好的写法?
public class OldArray {
/**
* @param args
*/
public int getCount(){
return num.length;
}
public int num[];
public int[] OldArrayOne(int array[]){
int length = array.length;//这里用C++怎么实现?
int renum[] = new int[length];
int count = 0;
for(int i=0;i<length;i++){
if(array[i]%2 != 0){
renum[count] = array[i];
count++;
}
}
num = new int[count];
for(int i =0;i<count;i++){
num[i] = renum[i];
}
return num;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
OldArray arr = new OldArray();
int a[] = {1,2,3,4,5,6};
int lengthWhole = a.length;
int first[] = new int[lengthWhole];
first = arr.OldArrayOne(a);
int length = arr.getCount();
for(int i = 0;i<length;i++){
System.out.println(first[i]);
}
}
}
public static int[] oddArray(int[] arr) {
int[] data = {};
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 2 == 1) {
data = Arrays.copyOf(data, data.length + 1);
data[data.length - 1] = arr[i];
}
}
return data;
}