[LeetCode] Average Value of Even Numbers That Are Divisible by Three

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.

Note that the average of n elements is the sum of the n elements divided by n and rounded down to the nearest integer.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int averageValue(vector<int>& nums) {
int sum = 0;
int cnt = 0;
for(auto n : nums) {
if(n % 2 == 0 and n % 3 == 0) {
sum += n;
cnt += 1;
}
}
if(cnt == 0) return 0;
return sum / cnt;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/30/PS/LeetCode/average-value-of-even-numbers-that-are-divisible-by-three/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.