Grade 9 · Number sequences read one at a timeCitește în română

Counting elements with a property

Original: Numărarea elementelor cu o proprietate

O(n²)C++1744 lines1 example

The idea

n and n natural numbers are read. We count how many of them are even and how many have the last digit equal to the first. Each property has its own counter, starting at 0 and increased when the property holds.

Original description (Romanian)

Se citesc n și n numere naturale. Numărăm câte dintre ele sunt pare și câte au ultima cifră egală cu prima. Fiecare proprietate are contorul ei, pornit de la 0 și mărit când proprietatea are loc.

Complexity
O(n · k), where k is the maximum number of digits
Grade
Grade 9 (Clasa a IX-a)

Examples

Example 1

Input

6
4 717 10 3 828 15

Expected output

3 4

The code

Comments are in Romanian, as in the original collection. Edit freely: you can reset at any time.

numarare-cu-proprietate.cpp
/*
 * Titlu: Numărarea elementelor cu o proprietate
 * Clasa: 9
 * Capitol: Șiruri de numere citite pe rând
 * Descriere: Se citesc n și n numere naturale. Numărăm câte dintre ele sunt
 *            pare și câte au ultima cifră egală cu prima. Fiecare proprietate
 *            are contorul ei, pornit de la 0 și mărit când proprietatea are loc.
 * Complexitate: O(n · k), unde k este numărul maxim de cifre
 *
 * Exemplu
 * Intrare:
 * 6
 * 4 717 10 3 828 15
 * Ieșire: 3 4
 */
#include <iostream>
using namespace std;

int main()
{
    int n, pare = 0, capete = 0;
    long long x;
    cin >> n;
    for (int i = 1; i <= n; i++)
    {
        cin >> x;
        if (x % 2 == 0)
        {
            pare++;
        }
        long long prima = x;
        while (prima >= 10)
        {
            prima = prima / 10;
        }
        if (prima == x % 10)
        {
            capete++;
        }
    }
    cout << pare << ' ' << capete << '\n';
    return 0;
}

Runs on a real g++ (C++17, -O2) through Compiler Explorer. Keep runs short; there's a time limit.