[英]Remove Leading Zeros
我试图弄清楚如何从数组中删除前导零。 该阵列当前存储在第一个位置的最低有效位。
示例:如果number为1101,则将其存储在我的数组中:[1,1,0,1]。 除了删除前导零之外,我不想翻转数组或改变它。 我有需要删除的前导零加粗。
我试图只使用数组而不是转换它
例如:电流输出:0 1 1 0
预期输出: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;
}
您的问题是输出数组与输入数组的大小相同...您跳过的0
仍将存在,因为0
是int[]
中任何项的默认值。
所以,我会从输入数组的末尾开始,而不是实际初始化输出数组,直到你达到第一个1
。 然后你知道输出数组有多大。
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;
}
向后遍历数组并找到最后一个出现的索引1
(或者到达数组的前面)。 然后将数组复制到该索引并包含该索引。 因为您知道最终数组的索引,所以您知道返回数组的大小(size lastIndex + 1
)
我编写java代码已经有一段时间了,所以这可能无法编译或正常运行。 但是这个代码可能如下所示:
public static byte[] normal(byte[] arr)
{
//null check arr if desired
int indexOfLastNonZero = arr.length - 1;
boolean foundOne = false;
while(!foundOne && indexOfLastNonZero >= 0)
{
if (arr[indexOfLastNonZero] == (byte) 1)
foundOne = true;
else
indexOfLastNonZero -= 1;
}
if (foundOne)
{
byte[] output = new byte[indexOfLastNonZero + 1];
System.arraycopy( arr, 0, output, 0, output.length );
return output;
}
else
{
return null; //or size 0 array if you prefer
}
}
你的output
数组太长了。 首先,你应该计算你拥有多少个前导零,并创建一个比arr
短的输出数组但是有很多元素:
public static byte[] normal(byte[] arr)
{
// Count the leading zeros:
int zeroes = 0;
while (arr[zeroes] == 0) {
++zeroes;
}
//check if all the numbers are 0 and last is 1
byte[] output = new byte[arr.length - zeroes];
for(int i = output.length - 1; i >= 0; ++i) {
output[i] = arr[i - zeroes];
}
return output;
}
或者更好的是,使用内置的Arrays.copyOfRange
:
public static byte[] normal(byte[] arr)
{
// Count the leading zeros:
int zeroes = 0;
while (arr[zeroes] == 0) {
++zeroes;
}
//check if all the numbers are 0 and last is 1
return Arrays.copyOfRange(zeroes, arr.length);
}
我建议从最后一个开始count
连续零的数量,然后生成output
数组,该数组的count
大小小于原始大小...
public static byte[] normal(byte[] arr)
{
int count = 0;
for(int i = arr.length-1;i>=0;i--)
{
if(arr[i]==1){
break;
}
count++;
}
byte [] output = new byte[copy.length-count];
for(int i = 0;i<(copy.length-count);i++) {
output[i] = copy[i];
}
return output;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.