Count Negative Numbers in Array
Count Negative Numbers in Array
Description:
Count the number of negative numbers in the given array. Do not use any inbuilt methods.
Example 1:
Input: arr = [1, 5, -3, 2, 0, -8, 4]
Output: Sum of positive numbers = 37
Explanation: There are 2 negative numbers in the array.
Example 2:
Input: arr = [-2, -7, 10, 4, -6, 8]
Output: 3
Explanation: There are 3 negative numbers in the array.
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 int countNegativeNumbers(int[] arr) { int count = 0; for (int num : arr) { if (num< 0) { count++; } } return count; } public static void main(String[] args) { int[] exampleArr = {1, 5, -3, 2, 0, -8, 4}; int result = countNegativeNumbers(exampleArr); System.out.println(result); } }
Python Code:
def count_negative_numbers(arr): return sum(1 for num in arr if num< 0) # Example usage example_arr = [1, 5, -3, 2, 0, -8, 4]; result = count_negative_numbers(example_arr) print(result)
C++ Code:
#include <iostream> #include <vector> class HackerAlgo { public: static int countNegativeNumbers(const std::vector<int>&arr) { int count = 0; for (int num : arr) { if (num< 0) { count++; } } return count