Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Leading Zeros

Tags:

java

arrays

I am trying to figure out how to remove leading zeros from an array. The array is currently stored with the least significant bit at the first position.

Example: if number is 1101 it is stored in my array as: [1,1,0,1]. I do not want to flip the array or change it in anyway except remove the leading zeros. I have the bolded the leading zero that needs to be removed.

I am trying to just do this with just using the array and not converting it

Ex: current output : 0 1 1 0

Expected output: 0 1 1

public static byte[] normal(byte[] arr)
    {
        //check if all the numbers are 0 and last is 1
        byte [] output = new byte[copy.length];
        for(int i = arr.length;i<=0;i--)
        {
            if(arr[i]==1){          
                output[i]=copy[i];
            }

        }
        return output; 

    }
like image 254
jim Avatar asked Feb 10 '23 04:02

jim


1 Answers

Your problem is that the output array is the same size as the input array... the 0s that you skip are still going to be there because 0 is the default value of any item in an int[].

So, I would start at the end of your input array, and not actually initialize the output array until you hit the first 1. Then you know how big to make the output array.

public static byte[] normal(byte[] arr) {
    byte[] output = null;
    System.out.println(arr.length);
    for (int i = arr.length-1; i >= 0; i--) {
        if (arr[i] != 0) {
            if (output == null) {
                output = new byte[i+1];
            }
            output[i] = arr[i];
        }
    }

    if (output == null) { // cover case where input is all 0s
        output = new byte[0];
    }

    return output;
}
like image 196
dcsohl Avatar answered Feb 11 '23 19:02

dcsohl