Given a list of positive integers, your task is to remove all the even elements from the array and return only odd integers.
Example:
{2,3,4,5,7,8}
Ans:
{3,5,7}
Solution:
We simply count the number of even integers and we set the size of our result array.
We then iterate over the elements of the array and selectively put only the odd integers in to the result array
public static int[] RemoveEven(int[] nums) {
int count = 0;
for(int i=0; i<nums.Length; i++) {
if(nums[i] % 2 != 0) {
count++;
}
}
int [] result = new int [count];
int j=0;
for(int i=0; i<nums.Length; i++) {
if(nums[i] % 2 != 0) {
result[j] = nums[i];
j++;
}
}
return result;
}