Return an array where each zero value in the array is replaced by the largest odd value to the right of the zero in the array.

  Understand the problem by following Examples.

Ex1: [0, 7, 0, 3] → [7, 7, 3, 3]
Ex2: [0, 2, 0, 3] → [3, 2, 3, 3]
Ex3: [0, 1, 0] → [1, 1, 0]

Solution:-

public class array1 {

    public static void main(String[] args) {

        int [] a = {0,2,0,3};

        for (int i=0; i<a.length; i++){

        if (a[i]==0){

        for (int j=i+1; j<a.length; j++){

        if (a[j]%2!=0){

        a[i]=a[j];

        break;
           }
                }
            }
        }

        for (int k=0; k<a.length; k++){

            System.out.print(a[k] + " ");

        }
}}

0 comments:

Post a Comment