Find Negative Numbers in Array
Find Negative Numbers in Array
Description:
Print all the negative numbers from a given array, extracting and displaying only those values that are less than zero.
Example 1:
Input: arr = [1, 5, -3, 2, 0, -8, 4]
Output: [-3, -8]
Explanation: The negative numbers in the array are -3 and -8.
Example 2:
Input: arr = [-2, -7, 10, 4, -6, 8]
Output: [-2, -7, -6]
Explanation: The negative numbers in the array are -2, -7, and -6.
Constraints:
The array length |arr| is at least 1 and at most 10^5. Elements in the array are integers ranging from -10^9 to 10^9.
Java Code:
public class HackerAlgo { public static void printNegativeNumbers(int[] arr) { for (int num : arr) { if (num< 0) { System.out.print(num + " "); } } System.out.println(); } public static void main(String[] args) { int[] exampleArr = {1, 5, -3, 2, 0, -8, 4}; printNegativeNumbers(exampleArr); } }
Python Code:
def print_negative_numbers(arr): negatives = [num for num in arr if num< 0] print(negatives) # Example usage example_arr = [1, 5, -3, 2, 0, -8, 4] print_negative_numbers(example_arr)
C++ Code:
#include <iostream> #include <vector> class HackerAlgo { public: static void printNegativeNumbers(const std::vector<int>&arr) { for (int num : arr) { if (num< 0) { std::cout<<num<< " "; } } std::cout<< std::endl; } }; int main() { // Example usage std::vector<int>exampleArr = {1, 5, -3, 2, 0, -8, 4}; HackerAlgo::printNegativeNumbers(exampleArr); return 0; }
JavaScript Code:
class HackerAlgo { static printNegativeNumbers(arr) { const negatives = arr.filter(num =>num< 0); console.log(negatives); } } // Example usage constexampleArr = [1, 5, -3, 2, 0, -8, 4]; HackerAlgo.printNegativeNumbers(exampleArr);