Kingsfull123
Kingsfull123

Reputation: 503

Return the larger value if it is in the range 10..20

I am trying to work out this problem on codingbat and the problem is Given 2 positive int values, return the larger value that is in the range 10..20 inclusive, or return 0 if neither is in that range. The solution has been given below but I can not understand the first part as the comment says larger value is a, but the code says( b > a ) and what does this mean: int temp = a; a = b; b = temp;. Can anyone please explain it...

public int max1020(int a, int b) {
  // First make it so the bigger value is in a
  if (b > a) {
    int temp = a;
    a = b;
    b = temp;
  }

  // Knowing a is bigger, just check a first
  if (a >= 10 && a <= 20) return a;
  if (b >= 10 && b <= 20) return b;
  return 0;
}

Upvotes: 1

Views: 946

Answers (2)

Iakovos
Iakovos

Reputation: 1982

It says that if the value of b is greater than that of a, switch the 2 values. So, for example, if a = 10 and b = 15:

if (b > a) { is true so will get in the if

int temp = a; temp will take the value 10

a = b; a will take the value 15

b = temp; b will take the value 10

So, the values of a and b will be switched, if the value of b is greater than that of a. Therefore, a will have the bigger value.

Upvotes: 0

Eran
Eran

Reputation: 393851

The first if statement makes sure that a is not smaller than b (if a is smaller than b, it swaps a and b - that's what the 3 assignment statements involving the temp variable do).

The second if statement returns a if it's in the required range (and at this point we know a >= b).

If not, the third if statement returns b if it's in the required range.

Otherwise 0 is returned (when both a and b are not in the required range).

Upvotes: 2

Related Questions