gpt4 book ai didi

java - 简单的二十一点

转载 作者:行者123 更新时间:2023-11-30 06:23:01 30 4
gpt4 key购买 nike

问题是:给定 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,对于它显示的所有测试,这段代码都有效,但是当它完成并显示“其他测试”时,这段代码失败了。我想在某些情况下这是行不通的,但我现在想不起来。有什么想法吗?

最佳答案

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。

关于java - 简单的二十一点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18649606/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com