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

Sum of the digits of a number

Original: Suma cifrelor unui număr

O(n)C++1729 lines1 example

The idea

Adds up the digits of n. The last digit is obtained with n % 10, then removed with n / 10. We repeat until n becomes 0.

Original description (Romanian)

Adună cifrele lui n. Ultima cifră se obține cu n % 10, apoi este eliminată cu n / 10. Repetăm până când n devine 0.

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

Examples

Example 1

Input

2025

Expected output

9

The code

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

suma-cifrelor.cpp
/*
 * Titlu: Suma cifrelor unui număr
 * Clasa: 9
 * Capitol: Cifrele unui număr
 * Descriere: Adună cifrele lui n. Ultima cifră se obține cu n % 10, apoi este
 *            eliminată cu n / 10. Repetăm până când n devine 0.
 * Complexitate: O(k), unde k este numărul de cifre ale lui n
 *
 * Exemplu
 * Intrare: 2025
 * Ieșire: 9
 */
#include <iostream>
using namespace std;

int main()
{
    long long n;
    int suma = 0;
    cin >> n;
    while (n > 0)
    {
        suma = suma + n % 10;
        n = n / 10;
    }
    cout << suma << '\n';
    return 0;
}

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