Menu Close

Leetcode 2455: Average Value of Even Numbers That Are Divisible by Three Solution

Here, we will see how to solve Average Value of Even Numbers That Are Divisible by Three Solution of leet code 2455 problem.

You are given an integer array nums of positive integers. You have to 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.

Example 1:

Input: nums = [1,3,6,10,12,15]
Output: 9
Explanation: 6 and 12 are even numbers that are divisible by 3. (6 + 12) / 2 = 9.

Example 2:

Input: nums = [1,2,4,7,10]
Output: 0
Explanation: There is no single number that satisfies the requirement, so return 0.

Average Value of Even Numbers That Are Divisible by Three Solution code in C++

Code 1:

class Solution {
public:
    int averageValue(vector<int>& nums) {
        int n = 0;
        float sum = 0.0, d = 0.0;
        
        for(auto &it : nums) {
            if((it & 1) == 0 && (it % 3) == 0) {
                n++;
                sum += it;
            }
        }
        cout<<sum<<n;
        if(n == 0) {
            return 0;
        } else {
            d = sum / n;
            return int(d);
        }
        
    }
};

Code 2:

class Solution {
public:
    int averageValue(vector<int>& nums) {
        int total = 0;
        int cnt = 0;
        for (auto num : nums) {
            if (num % 6 == 0) {
                ++cnt;
                total += num;
            }                
        }
        return ceil(cnt!=0)?total/cnt:0;
    }
};

Output:

Input: nums = [1,3,6,10,12,15]
Output: 9

To check more leetcode problem’s solution. Pls click given below link:

https://www.techieindoor.com/category/leetcode/

Posted in C++, Easy, Leetcode

Leave a Reply

Your email address will not be published. Required fields are marked *