Grade 9 · Digits of a numberCitește în română

Product of the digits of a number

Original: Produsul cifrelor unui număr

O(n)C++1734 lines2 examples

The idea

Multiplies the digits of n. The product starts from 1 (the identity element of multiplication), not from 0. With do-while, for n = 0 we correctly get the product 0 (the only digit is 0).

Original description (Romanian)

Înmulțește cifrele lui n. Produsul pornește de la 1 (elementul neutru al înmulțirii), nu de la 0. Cu do-while, pentru n = 0 se obține corect produsul 0 (singura cifră este 0).

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

Examples

Example 1

Input

234

Expected output

24
Example 2

Input

0

Expected output

0

The code

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

produsul-cifrelor.cpp
/*
 * Titlu: Produsul cifrelor unui număr
 * Clasa: 9
 * Capitol: Cifrele unui număr
 * Descriere: Înmulțește cifrele lui n. Produsul pornește de la 1 (elementul
 *            neutru al înmulțirii), nu de la 0. Cu do-while, pentru n = 0 se
 *            obține corect produsul 0 (singura cifră este 0).
 * Complexitate: O(k), unde k este numărul de cifre ale lui n
 *
 * Exemplu
 * Intrare: 234
 * Ieșire: 24
 *
 * Exemplu
 * Intrare: 0
 * Ieșire: 0
 */
#include <iostream>
using namespace std;

int main()
{
    long long n, produs = 1;
    cin >> n;
    do
    {
        produs = produs * (n % 10);
        n = n / 10;
    }
    while (n > 0);
    cout << produs << '\n';
    return 0;
}

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