Leetcode 2455. Average Value of Even Numbers That Are Divisible by Three
Given an integer array nums
of positive integers, return the average value of all even integers that are divisible by 3
. If there are no such integers, return 0
.
0
since there are no integers to consider.0
if there are no even integers divisible by 3
.3
.0
; otherwise, return 0
.#include <vector>
using namespace std;
class Solution {
public:
int averageValue(vector<int>& nums) {
int sum = 0;
int count = 0;
for (int num : nums) {
if (num % 6 == 0) {
sum += num;
count++;
}
}
return count > 0 ? sum / count : 0;
}
};
sum
to 0
and count
to 0
.2
and 3
which is equivalent to checking num % 6 == 0
.sum
and increment count
.count
is greater than 0
, we return the integer division result of sum
divided by count
. Otherwise, we return 0
.sum
and count
).This solution is efficient and concise, adhering to the requirements of the problem.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?