Skip to the content

Closest to the target

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):
    pass

JavaScript

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

See all challenges →