Average Value of Even Numbers That Are Divisible by Three

Here’s the Python code for the problem to calculate the average of all even integers that are divisible by 3:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
    def averageValue(self, nums: List[int]) -> int:
        total_sum = 0
        count = 0

        for num in nums:
            if num % 2 == 0 and num % 3 == 0:
                total_sum += num
                count += 1

        if count == 0:
            return 0
        
        return total_sum // count

Explanation

  • We initialize two variables total_sum and count to keep track of the total sum of numbers that meet the criteria and the count of those numbers.
  • We iterate through the nums array and check if a number is both even (num % 2 == 0) and divisible by 3 (num % 3 == 0).
  • If the number meets the criteria, we add it to total_sum and increment the count.
  • After the loop, if count is 0, it means no numbers met the criteria, so we return 0.
  • Otherwise, we return the integer division of total_sum by count, which gives the average rounded down to the nearest integer.