Count Total Positives, Negatives, and Zeros from an Array
Count Total Positives, Negatives, and Zeros from an Array
Description:
Given an array arr[] of integers, write a program to count the number of positive, negative, and zero numbers present in the array.
Example 1:
Input: arr = {1, -2, 3, 0, -5}
Output: Positive: 2, Negative: 2, Zero: 1
Explanation: There are 2 positive numbers (1, 3), 2 negative numbers (-2, -5), and 1 zero (0) in the array.
Example 2:
Input: arr = {0, 0, 0, 0, 0}
Output: Positive: 0, Negative: 0, Zero: 5
Explanation: All elements in the array are zero.
Constraints:
The array length |arr| is at least 1 and at most 10^5.
Java Code:
public class HackerAlgo { // Count Total Positives, Negatives, and Zeros public static void countPositivesNegativesZeros(int[] arr) { int positiveCount = 0; int negativeCount = 0; int zeroCount = 0; for (int num : arr) { if (num> 0) { positiveCount++; } else if (num< 0) { negativeCount++; } else { zeroCount++; } } System.out.println("Positive: " + positiveCount + ", Negative: " + negativeCount + ", Zero: " + zeroCount); } public static void main(String[] args) { // Example for Count Total Positives, Negatives, and Zeros int[] arr1 = {1, -2, 3, 0, -5}; countPositivesNegativesZeros(arr1); int[] arr2 = {0, 0, 0, 0, 0}; countPositivesNegativesZeros(arr2
Python Code:
# Count Total Positives, Negatives, and Zeros def count_positives_negatives_zeros(arr): positive_count = sum(1 for num in arr if num> 0) negative_count = sum(1 for num in arr if num< 0) zero_count = len(arr) - positive_count - negative_count print(f"Positive: {positive_count}, Negative: {negative_count}, Zero: {zero_count}") # Example usage arr1 = [1, -2, 3, 0, -5] count_positives_negatives_zeros(arr1) arr2 = [0, 0, 0, 0, 0] count_positives_negatives_zeros(arr2
C++ Code:
#include <iostream> #include <vector> class HackerAlgo { public: // Count Total Positives, Negatives, and Zeros static void countPositivesNegativesZeros(const std::vector<int>&arr) { int positiveCount = 0; int negativeCount = 0; int zeroCount = 0; for (int num : arr) { if (num> 0) { positiveCount++; } else if (num< 0) { negativeCount++; } else { zeroCount++; } } std::cout<< "Positive: " <<positiveCount<< ", Negative: " <<negativeCount<< ", Zero: " <<zeroCount<< std::endl; } }; int main() { // Example for Count Total Positives, Negatives, and Zeros std::vector<int> arr1 = {1, -2, 3, 0, -5}; HackerAlgo::countPositivesNegativesZeros(arr1); std::vector<int> arr2 = {0, 0, 0, 0, 0}; HackerAlgo::countPositivesNegativesZeros(arr2); return 0
JavaScript Code:
class HackerAlgo { // Count Total Positives, Negatives, and Zeros static countPositivesNegativesZeros(arr) { constpositiveCount = arr.filter(num =>num> 0).length; constnegativeCount = arr.filter(num =>num< 0).length; constzeroCount = arr.length - positiveCount - negativeCount; console.log(`Positive: ${positiveCount}, Negative: ${negativeCount}, Zero: ${zeroCount}`