【问题标题】:Easiest way to check integer is either +1 or -1 Java检查整数的最简单方法是 +1 或 -1 Java
【发布时间】: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


【解决方案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

【讨论】:

    【解决方案2】:

    我能想到的最简单的方法是:

    boolean differenceOfOne = Math.abs(n1 - n2) == 1;
    

    其中n1n2 是数字。

    【讨论】:

      【解决方案3】:

      怎么样:

         Math.abs(difference)==1
      

      【讨论】:

        【解决方案4】:

        您可以使用Math.abs 来评估差异:

        boolean isDifferenceOne = Math.abs(x1 - x2) == 1 && Math.abs(y1 - y2) == 1
        

        【讨论】:

          猜你喜欢
          • 2011-09-12
          • 1970-01-01
          • 2012-10-24
          • 1970-01-01
          • 2015-01-11
          • 2013-02-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多