Question

In: Computer Science

This is JAVA The mere presence of oversized arrays makes Priscilla Perfect sick to her stomach....

This is JAVA

The mere presence of oversized arrays makes Priscilla Perfect sick to her stomach. Such wasted space is an imperfection she cannot bear. As her oldest and dearest friend this worries you greatly. If you were a doctor you might try to find a cure to her sickness, but you are a programmer. A program must be written to alleviate her pain!

For any array given that has empty slots create a new array that is perfect. Unused slots will have a value of 0. All unused slots are guaranteed to be at the end of the array. There will never be unused slots in the middle.
java.util.Arrays has been enabled.

Examples:

makePerfect({1, 1, 4, 5, 6, 0, 0, 0, 0}) -> {1, 1, 4, 5, 6}

makePerfect({1, 3, 4, 2, 6, 0, 0, 0, 0}) -> {1, 3, 4, 2, 6}

1

public int[] makePerfect(int[] arr)

2

{

3

    

4

}

5

Solutions

Expert Solution

public class TestArr {
   public static void main(String[] args) {
       int arr[]= {1, 1, 4, 5, 6, 0, 0, 0, 0};
       int res[]=new TestArr().makePerfect(arr);
       for(int i=0;i<res.length;i++)
           System.out.print(res[i]+" ");
      
   }
   public int[] makePerfect(int[] arr) {
       int size=0;
       for(int i=0;i<arr.length;i++)
           if(arr[i]!=0)
               size++;
       int res[]=new int[size];
      
       for(int i=0,index=0;i< arr.length;i++) {
           if(arr[i]!=0) {
               res[index++]=arr[i];
           }
       }
       return res;
   }
}

NOTE : PLEASE COMMENT BELOW IF YOU HAVE CONCERNS.

I AM HERE TO HELP YOUIF YOU LIKE MY ANSWER PLEASE RATE AND HELP ME IT IS VERY IMP FOR ME


Related Solutions

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT