【发布时间】:2014-02-20 17:44:37
【问题描述】:
我想两个整数的差是+1还是-1。我认为我下面的代码写起来很笨拙。有没有更短的方法来检查两个整数是否仅相差 1?这似乎是一个简单的解决方案,但我有一个二维坐标数组,我想检查是否选择了彼此直接相邻的两个坐标(北、东、西或南)。
是的,它们是标准坐标,因为左上角是 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
}
【问题讨论】:
-
point1=(1,1) and point2=(2,2)的情况呢?
标签: java loops integer comparison