Sum two numbers to zero
JavaScript
Easy
Objective
Write a function that receives an array of numbers, and returns two that equal zero when added together.
Requirements
The function should be called
sumTwoNumbers
It will receive a single parameter, which is an array of numbers
It should return two numbers that add up to zero
If there are multiple pairs that sum to zero, the function can return any of them
If no two numbers add up to zero, the function should return
null
Check your solution
Tests
Function name is sumTwoNumbers | |||
sumTwoNumbers([-1,1,2,3]) | Expected: | [-1,1] | |
sumTwoNumbers([1,2,3,4]) | Expected: | null |
Solution
Here's how I would approach this, but keep in mind there might be other ways to solve this problem.
function sumTwoNumbers(numbers) {
// This approach uses a Set, they were added in ES^
// Create a set to store the numbers
let numSet = new Set();
// Loop through the numbers
for (let num of numbers) {
// Check if the set contains the negative of the current number
if (numSet.has(-num)) {
// If it does, return the negative and the positive
return [-num, num];
}
numSet.add(num);
}
// Return null if no pair is found
return null;
}
Click to reveal