0

我遇到了下面的问题,但是无论我采取什么方法,我都无法让它通过所有测试。谁能指出我哪里出错了?

该问题必须使用 Math.abs() 和 IF 语句来解决,没有循环/函数/等。

////////////////////////////// PROBLEM STATEMENT //////////////////////////////
// Given three ints, a b c, print true if one of b or c is "close"           //
// (differing from a by at most 1), while the  other is "far", differing     //
// from both other values by 2 or more. Note: Math.abs(num) computes the     //
// absolute value of a number.                                               //
//   1, 2, 10 -> true                                                        //
//   1, 2, 3 -> false                                                        //
//   4, 1, 3 -> true                                                         //
///////////////////////////////////////////////////////////////////////////////

我的代码:

  if ((Math.abs(a-b) <= 1 || Math.abs(a+b) <= 1) && (Math.abs(a-c) >= 2 || Math.abs(a+c) >= 2)) {

    if (Math.abs(a-c) >= 2 || Math.abs(a+c) >= 2) {
      System.out.println("true");
    } else {
      System.out.println("false");
    }

  } else if (Math.abs(a-c) <= 1 || Math.abs(a+c) <= 1) {

    if (Math.abs(a-b) >= 2 || Math.abs(a+b) >= 2) {
      System.out.println("true");
    } else {
      System.out.println("false");
    } 

  } else {
     System.out.println("false"); 
    }
4

2 回答 2

1

似乎过于复杂,您可能想要更简单的东西:

boolean abIsClose = Math.abs(a-b) <= 1;
boolean acIsClose = Math.abs(a-c) <= 1;
boolean bcIsClose = Math.abs(b-c) <= 1;
boolean result = abIsClose && !acIsClose && !bcIsClose;
result = result || (!abIsClose && acIsClose && !bcIsClose);
result = result || (!abIsClose && !acIsClose && bcIsClose);

Abs 总是给出一个正数,这样你就不需要确认一个值在 -1 和 1 之间,你只需要确认 <= 1。

于 2013-03-21T08:51:04.607 回答
0

您可以将其分解为两种可能的情况true

  1. b近而c
  2. c近而b

现在,1. 是什么意思?

  • b很近 -Math.abs(a-b) <= 1
  • c很远 -Math.abs(a-c) >= 2 && Math.abs(b-c) >= 2

所以我们最终得到

if (Math.abs(a - b) <= 1 && Math.abs(a - c) >= 2 && Math.abs(b - c) >= 2) {
    return true;
}

现在将相同的逻辑应用于第二个条件:

if (Math.abs(a - c) <= 1 && Math.abs(a - b) >= 2 && Math.abs(b - c) >= 2) {
    return true;
}

所以最终的方法看起来像:

public static boolean myMethod(int a, int b, int c) {
    if (Math.abs(a - b) <= 1 && Math.abs(a - c) >= 2 && Math.abs(b - c) >= 2) {
        return true;
    }
    if (Math.abs(a - c) <= 1 && Math.abs(a - b) >= 2 && Math.abs(b - c) >= 2) {
        return true;
    }
    return false;
}

输出:

public static void main(String[] args) {
    System.out.println(myMethod(1, 2, 10));
    System.out.println(myMethod(1, 2, 3));
    System.out.println(myMethod(4, 1, 3));
}
true
false
true
于 2013-03-21T08:54:23.973 回答