[英]Easiest way to check integer is either +1 or -1 Java
我想要两个整数之间的差是+1或-1。 我认为下面的代码编写起来很笨拙。 有没有更短的方法来检查两个整数是否仅相隔1? 这似乎是一个简单的解决方案,但是我有2d坐标数组,我想检查是否选择了彼此直接相邻的两个坐标(北,东,西或南) 。
是的,它们是标准坐标,因为左上角为0,0,右下角为7,7。 本质上,如果选择了一个坐标,我想检查是否存在另一个坐标,其中x或y相差(+-)一个。
//Since it's a 2d array, I am doing a nested loop. But comparison is below
int x1 = range(0,8); //all ints are range from 0 to 7
int y1 = range(0,8); //represent the current indices from the loop
int x2 = ...; //x2 represents the x index value of the previous loop
int y2 = ...; //y2 represents the y index value of the previous loop
if(x1+1 == x2){
Found an existing X coord just larger by one
}else if (x1-1 == x2){
Found an existing X coord smaller, and differ by one
}else if(y1+1 == y2){
Found an existing Y coord just 1 larger
}else if(y-1 == y2){
Found an existing Y coord just 1 smaller
}
我能想到的最简单的方法是:
boolean differenceOfOne = Math.abs(n1 - n2) == 1;
其中n1
和n2
是数字。
怎么样:
Math.abs(difference)==1
您可以使用Math.abs
评估差异:
boolean isDifferenceOne = Math.abs(x1 - x2) == 1 && Math.abs(y1 - y2) == 1
由于我们不在乎x1和x2之间的差是1还是-1,因此我们可以使用绝对值:
if (Math.abs(x1 - x2) == 1){
// x coordinates differ by 1
} else if (Math.abs(y1 - y2) == 1){
// y coordinates differ by 1
}
之所以有效,是因为如果x1
小于x2
,则Math.abs(x1 - x2) = Math.abs(-1) = 1
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.