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

これを 2 つの状況に分けることができます。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;
}

同じロジックを 2 番目の条件に適用します。

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 に答える