Remove Even Numbers From Array

By   Tewodros   Date Posted: Feb. 20, 2022  Hits: 1,050   Category:  Algorithm   Total Comment: 0             A+ A-


side

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;

   }


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* cieggl

Back to Top