Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to replace zeros in the array, with elements of another array in java

import java.util.Arrays;
public class Main
{
public static void main(String[] args) {

    int[] a = {1,2,3,0,0,0};
    int[] b = {7,9,13};
    
    //resultant array: a={1,2,3,7,9,13}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Iterate through array A and replace elements with value zero with elements from B.

int n = a.length();
int m = b.length();
int j = 0;
for(int i=0; i<n; i++){
  if(a[i] == 0 && j<m){a[i]=b[j];j++;}
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading