More effective blackjack solution?

I am working on the following problem from codingbat:

Given 2 int values โ€‹โ€‹greater than 0, return any value closest 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:

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 anything in my logic that can be improved to make it more efficient? Am I doing something unnecessary?

+6
source share
4 answers

It may be more effective. At least this is another way to look 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; } } 
+4
source

I would not say that this is more efficient, but I re-ordered some of the if statements and came to the code below. I think this is at least somewhat simpler:

 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; } 
+2
source

It can be pretty close;

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

+2
source

Using the ternary operator:

 public int blackjack(int a, int b) { a = a > 21 ? 0 : a; b = b > 21 ? 0 : b; return (a > b) ? a : b; } 
+1
source

Source: https://habr.com/ru/post/894897/


All Articles