找到它们之间的绝对差异
Math.abs
private boolean close(int i, int j, int closeness){ return Math.abs(i-j) <= closeness; }基于@GregS关于溢出的评论,如果您给出
Math.abs的差值不能适合整数,您将获得一个溢出值
Math.abs(Integer.MIN_VALUE - Integer.MAX_VALUE) //gives 1
通过将其中一个参数强制转换为long
Math.abs将返回long,表示将正确返回差值
Math.abs((long) Integer.MIN_VALUE - Integer.MAX_VALUE) //gives 4294967295
因此,考虑到这一点,该方法现在将如下所示:
private boolean close(int i, int j, long closeness){ return Math.abs((long)i-j) <= closeness; }


