Reputation: 37
I am doing java exercise in coding bat and came across the following question. Honestly, I could not figure out the question and looked for the solution. Can you guys please explain me the below code and how the logic works?
Question:
Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.
diff21(19) → 2 diff21(10) → 11 diff21(21) → 0
Solution code. Why do we need to subtract the N from 21?
public int diff21(int n) {
if (n <= 21) {
return 21 - n;
} else {
return (n - 21) * 2;
}
}
Upvotes: 0
Views: 2016
Reputation:
#Coding bat problem warmup-1 diff21
Question: Given an int n, return the absolute difference between n and 21, except return double the absolute difference if n is over 21.
Solution:
def diff21(n):
if n > 21:
return 2*abs(21 - n)
else:
return abs(21 - n)
Upvotes: -2
Reputation: 47
To find the difference between two numbers is to find how far apart the two numbers are from eachother.
For example the difference between 1 and 7 is 6, which can be found by doing 7-1. You have to subtract the larger value from the smaller value in order to find the difference, otherwise you will end up with an incorrect number.
In your example if the code if(n<=21)
returns true
then the value of n
will be less than or equal to 21 which means that it is safe to do 21-n
.
If you did not use the if-else statement and instead your code only had return 21-n;
then if the value of n
was larger than 21, a negative number would be returned which would be incorrect.
Upvotes: 1
Reputation: 531
You have to subtract N from 21 because absolute value is the positive difference between 2 numbers. n-21
is invalid because if n is larger than 21, the program will just return double n
, so you know that n
should never be larger than 21. Therefore, n-21
would always return a negative value, which shouldn't happen because the exercise requires absolute value, which is always positive.
Upvotes: 1
Reputation: 130
If n > 21:
# as quoted: "double the absolute difference"
else:
# return just the absolute difference
An absolute number is always positive (a real number).
https://en.wikipedia.org/wiki/Absolute_value
Upvotes: 1