700824. Count Odd Even - Java
Easy
Here is a detailed Markdown blog post for the problem:
Count Odd Even - Java
Summary
Given an array of integers, count and separate the odd and even numbers. This problem involves basic array manipulation and conditional statements.
Detailed Explanation
To solve this problem, we can iterate through the given array and check each number to see if it's odd or even. We'll use a counter variable for both odd and even counts.
Here's the step-by-step breakdown:
- Initialize two counters:
oddCountandevenCount, set them to 0. - Iterate through the given array.
- For each number in the array, check if it's odd or even using a conditional statement.
- If the number is odd, increment the
oddCount. If it's even, increment theevenCount. - Return the counts as separate results.
Time complexity: O(n), where n is the size of the input array. Space complexity: O(1), because we only use a constant amount of space to store the counters and variables.
Optimized Solutions
Java
public class Main {
public static void main(String[] args) {
int[] nums = {1, 2, 3, 4, 5};
int oddCount = 0;
int evenCount = 0;
for (int num : nums) {
if (num % 2 != 0) {
oddCount++;
} else {
evenCount++;
}
}
System.out.println("Odd count: " + oddCount);
System.out.println("Even count: " + evenCount);
}
}