2

问题来了:给定 2 个大于 0 的 int 值,返回最接近 21 的值,不要越过。如果他们都过去,则返回 0。

blackjack(19, 21) → 21
blackjack(21, 19) → 21
blackjack(19, 22) → 19

到目前为止我所拥有的:

 public int blackjack(int a, int b) {
  if (a>21 && b>21){
  return 0;
  }
  if (a<21 && b>21){
  return a;
  }
  if (b<21 && a>21){
  return b;
  }
  if (21-a < 21-b){
  return a;
  }
  return b;
}

这个问题来自codingbat.com,对于它显示的所有测试,这段代码都有效,但是当它完成并显示“其他测试”时,这段代码失败了。我想在某些情况下这是行不通的,但我现在想不出。有什么想法吗?

4

3 回答 3

3
public int blackjack(int a, int b) {
// if both a and b are outside the valid range
if (a > 21 && b > 21)
  return 0;

// if a is within the valid range but b is not
if (a <= 21 && b > 21)
  return a;

// if b is within the valid range but a is not
if (b <= 21 && a > 21)
  return b;

// if both a and be are within the valid range
return (a-b >= 0) ? a : b;

// Alternative: return Math.max(a, b);    ---as per SimonT in the comment
}

所以我猜你的问题是你的条件中没有包括 21 。

于 2013-09-06T04:00:28.150 回答
1

您忘记=在您的条件下指定操作。将第二个和第三个条件更改为:

if (a<=21 && b>21){
  return a;
}
if (b<=21 && a>21){
  return b;
}
于 2013-09-06T04:03:24.567 回答
1

如果a=21,b=22,那么它会返回不正确的b。

于 2013-09-06T04:00:07.487 回答