Coding problem · Easy · Basics
Count the Even Numbers
Easy Algorithms & data structures
Return how many numbers in nums are even (divisible by 2). Negative numbers and zero count too.
Example 1
Input: nums = [1,2,3,4,6] Output: 3
Example 2
Input: nums = [1,3,5] Output: 0
Hints
Hint 1
A number is even when n % 2 === 0.
Write and run your solution
Loading the editor… (JavaScript is required to run code in your browser.)
Solution and explanation
Show the solution
Time O(n) · Space O(1)
Loop and count elements where n % 2 == 0. In some languages -3 % 2 is -1, so compare with 0 rather than checking for 1.
Reference solution
function countEvens(nums) {
return nums.filter((n) => n % 2 === 0).length;
}
function countEvens(nums: number[]): number {
return nums.filter((n) => n % 2 === 0).length;
}
def count_evens(nums: list[int]) -> int:
return sum(1 for n in nums if n % 2 == 0)
<?php
function countEvens(array $nums): int
{
return count(array_filter($nums, fn ($n) => $n % 2 === 0));
}
class Solution {
public int countEvens(int[] nums) {
int count = 0;
for (int n : nums) if (n % 2 == 0) count++;
return count;
}
}
More Basics problems
- Reverse a String · Easy
- Count the Vowels · Easy
- Capitalize Each Word · Easy
- Longest Word in a Sentence · Easy
- Run-Length Encoding · Easy
- Is It a Pangram? · Easy