繁体   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