Constructing a Number

Manipulating numbers is at the core of a programmer's job. To test how well you know their properties, you are asked to solve the following problem.

You are given n non-negative integers , ..., . You want to know whether it's possible to construct a new integer using all the digits of these numbers such that it would be divisible by 3. You can reorder the digits as you want. The resulting number can contain leading zeros.

For example, consider the numbers from which you have to construct a new integer as described above. Numerous arrangements of digits are possible, but we have illustrated one below.

image

Complete the function canConstruct which takes an integer array as input and return "Yes" or "No" based on whether or not the required integer can be formed.

Example:

Input: n = 3, a = {40, 50, 90}
Output: Yes

Approach

C++

#include <bits/stdc++.h>
using namespace std;

string canConstruct(vector<inta)
{
    int n = a.size();

    string str[n];
    for (int i = 0i < ni++)
        str[i= to_string(a[i]);
    int cnt = 0;
    for (int i = 0i < ni++)
    {
        for (int j = 0j < (int)str[i].size(); j++)
        {
            cnt += str[i][j] - '0';
        }
    }
    if (cnt % 3 == 0)
        return "Yes";
    else
        return "No";
}

int main()
{
    int n = 3;
    vector<inta = {405090};

    cout << canConstruct(a<< "\n";

    return 0;
}


No comments:

Post a Comment