Closest to the target
- O(1) · Trivial
- Free
- Python
- JavaScript
- conditionals
- comparisons
- operations
Problem
Write a function that takes two numbers, a and b, plus a target, and returns whichever of the two lands closer to the target: with 4, 9 and a target of 6 you return 4, because 4 is 2 short and 9 is 3 over. If both are the same distance away, return the bigger one.
The numbers can be negative.
Examples
4, 9, 6 → 4
The second one wins
1, 8, 7 → 8
All negative
-7, -2, -4 → -2
Besides these, the challenge has hidden tests that are revealed when you submit your solution.
You start with this
Python
def closest(a, b, target):
passJavaScript
function closest(a, b, target) {
}Solve this challenge
It opens in your browser, with the editor and the tests. It is free and you do not need an account to start.
More O(1) challenges
- Coat or t-shirt?conditionals · strings · comparisons
- Did the fever go down?lists · indexes · booleans
- Did they pass the class?booleans · conditionals
- Digits the other way rounddigits · operations
- Do the two times overlap?conditionals · booleans · comparisons
- Does it fall in range?conditionals · booleans · comparisons