我有一个大小为14的数字数组,其中填充-1,其中空白,其余的数字如下例2,3,4,7,8,-1,-1.
我如何比较这些数字,使它们相隔1,并从中取第一个和最后一个数字。所以在这里,我会比较,2,3,x=1,x,4,4,x=3,我取2作为第一个数,4作为最后一个数,然后比较另一半,这样,7是第一个数,8是最后一个数。
int diff = 0;
int firstNum = 0;
int lastNum = 0;
for (int j=0; j < temp.length; j++){
if (temp[j] != -1){
diff = Math.abs(temp[j] - temp[j+1]);
if (diff <= 1){
// first and last number
firstNum = temp[j];
lastNum = temp[j+1];
}
else {
firstNum = temp[j];
lastNum = temp[j+1];
}
}
}发布于 2016-02-07 15:37:38
你可以试试这个:
int diff = 0;
int firstNum = temp[0];
int lastNum = temp[0];
for (int j=0; j < temp.length - 1; j++){
if (temp[j] != -1){
diff = Math.abs(temp[j] - temp[j+1]);
if (diff <= 1){
// last number
lastNum = temp[j+1];
}
else {
System.out.println("First number: " + firstNum + ", last number: " + lastNum);
firstNum = temp[j+1];
lastNum = temp[j+1];
}
}
}发布于 2016-02-07 15:48:32
试试这个.
int diff = 0;
bool flag = false;
int firstNum = 0;
int lastNum = 0;
for (int j=0; j < temp.length-1; j++){
if (temp[j] != -1 && temp[j+1] != -1){
diff = Math.abs(temp[j] - temp[j+1]);
if (diff <= 1){
if(firstNum == 0)
firstNum = temp[j];
lastNum = temp[j+1];
flag = false;
}
else {
System.out.println(firstNum + ", " + lastNum);
firstNum = 0;
flag = true;
}
}
if (!flag)
System.out.println(firstNum + ", " + lastNum);
}如果我不做旗子的事,它会打印两次。也许还有其他有效的方法来做到这一点。
https://stackoverflow.com/questions/35255326
复制相似问题