Find Closest Number to Zero in an Array

Easy
12
69.6% Acceptance

In this lab, you will write a function that finds the number closest to zero in an integer array. The function should return the number with the highest value if there are multiple answers. The lab provides various test cases to validate your implementation.

Function signature:

/** * @param {number[]} nums * @return {number} */ var findClosestNumber = function(nums) { };

Your task is to implement the findClosestNumber function.

Examples:

Example 1:

findClosestNumber([-4, -2, 1, 4, 8]);

Output: 1

Explanation:

The distance from -4 to 0 is |-4| = 4. The distance from -2 to 0 is |-2| = 2. The distance from 1 to 0 is |1| = 1. The distance from 4 to 0 is |4| = 4. The distance from 8 to 0 is |8| = 8. Thus, the closest number to 0 in the array is 1.

Example 2:

findClosestNumber([2, -1, 1]);

Output: 1

Explanation: 1 and -1 are both the closest numbers to 0, but 1 is the largest, so it is returned.

Constraints:

  • 1 <= nums.length <= 1000
  • -105 <= nums[i] <= 105

Challenges

  1. Implement the findClosestNumber function.
  2. Export the findClosestNumber function using ESM import/export syntax.
  3. Pass all the test cases provided in the evaluation script.

Evaluation

Your solution will be evaluated based on the following criteria:

  • The implemented function meets the challenge requirements.
  • The code is well-organized and easy to read.
  • The final length of the testlog array in the evaluation script matches the number of challenges.
  • The order of evaluation script try-catch blocks follows the order of the challenges.
  • Proper use of ESM import/export syntax throughout the solution.