[英]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.