簡體   English   中英

JAVA-找出差異

[英]JAVA - Figuring out the difference

我遇到了以下問題,但是無論采用哪種方法,我都無法使其通過所有測試。 誰能指出我要去哪里了?

必須使用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"); 
    }

似乎過於復雜,您可能想采用更簡單的方法:

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。

你可以將其分為兩種可能的情況時,它的true

  1. b很近, c很遠
  2. c很近, b很遠

現在,1.是什么意思?

  • b關閉Math.abs(ab) <= 1
  • c很遠Math.abs(ac) >= 2 && Math.abs(bc) >= 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM