I'm working on the following problem from codingbat:
Given 2 int values greater than 0, return whichever value is nearest to 21 without going over. Return 0 if they both go over.
blackjack(19, 21) → 21
blackjack(21, 19) → 21
blackjack(19, 22) → 19
My solutions is:
public int blackjack(int a, int b) {
if (a>21){
if (b>21){
return 0;
}
return b;
}
else if(b>21) return a;
return Math.max(a,b);
}
Is there something in my logic that can be improved to make it more efficient? Am I doing something unnecessary?
This could be more efficient. At the very least it's another way of looking at the problem:
public int blackjack(int a, int b) {
if (a>21) a = 0;
if (b>21) b = 0;
if (a>b) {
return a;
else {
return b;
}
}
I wouldn't say this is more efficient, but I re-ordered some of the if statements and arrived at the code below. I think this is, at the very least, somewhat easier to follow:
public int blackjack(int a, int b) {
if (a <= 21 && b <= 21) return Math.max(a, b);
if (a <= 21) return a;
if (b <= 21) return b;
return 0;
}
Using ternary operator:
public int blackjack(int a, int b) {
a = a > 21 ? 0 : a;
b = b > 21 ? 0 : b;
return (a > b) ? a : b;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With