Reduction of digits P96965


Statement
 

pdf   zip   main.cc   main.c   main.java   main.py

thehtml

Write a function that, given a natural number x, returns the reduction of its digits.

Interface

C++
int reduction_of_digits(int x);
C
int reduction_of_digits(int x);
Java
public static int reductionOfDigits(int x);
Python
reduction_of_digits(x) # returns int
 
reduction_of_digits(x: int) -> int

In this exercise, we say that reducing the digits of a number means computing the sum of its digits. If the sum has just one digit, this is already the result. Otherwise, we apply the same process again to the sum, until we get a single digit.

Solve this problem using a recursive function to return the sum of the digits of a natural number x.

Interface

C++
int sum_of_digits(int x);
C
int sum_of_digits(int x);
Java
public static int sumOfDigits(int x);
Python
sum_of_digits(x) # returns int
 
sum_of_digits(x: int) -> int

Precondition

x is a natural number.

Observation

Although there is a mathematic trick to solve this problem faster than by adding up its digits, do not use it here.

Observation You only need to submit the required procedure; your main program will be ignored.

Public test cases
  • Input/Output

    reduction_of_digits(33) → 6
    reduction_of_digits(5699) → 2
    reduction_of_digits(0) → 0
  • Information
    Author
    Jordi Petit
    Language
    English
    Translator
    Carlos Molina
    Original language
    Catalan
    Other languages
    Catalan
    Official solutions
    C C++ Java Python
    User solutions
    C C++ Java Python