Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing zeros in the output of an integer array in java

Tags:

java

In my code, I get an output of an array but it displays some unwanted zeros after getting the array, Can you explain a way to avoid getting these unwanted zeros.

 static int[] cutTheSticks(int[] arr) {
 int min,i,j,count=0;
 int []arr2=Arrays.copyOf(arr,arr.length);
 int []temp =Arrays.copyOf(arr,arr.length);


    for(i=0;i<arr.length;i++){
        Arrays.sort(arr2);
        min= arr2[0];
        for(j=0;j<arr.length;j++){

            if(temp[j]>0){
                count++;
            }
            temp[j]=temp[j]-min;

        }
        int []res = new int [arr.length];
        while(count!=0) {
            res[i] = count;
            count = 0;

    }
    return res;



  }
like image 831
Pulsara Sandeepa Avatar asked Jan 25 '26 23:01

Pulsara Sandeepa


1 Answers

You can figure the "size" of res without its trailing zeros with:

int rlen = res.length;
while (res[rlen-1] == 0) {
    --rlen;
}

If you wish, you can then use the calculated "effective length" rlen to reallocate the res array at the correct size:

res = Arrays.copyOf(res, rlen);

Or just use rlen instead of res.length when you need to know the "correct" size of res.

like image 147
Kevin Anderson Avatar answered Jan 27 '26 15:01

Kevin Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!