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;
}
Your problem is that the output array is the same size as the input array... the 0
s 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With