Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
Recursive digits sum without the right digit

I need to write a recursive function that will sum all the digits of the given number exept of the most right digit. For example: 56643 -> 5 + 6 + 6 + 4 = 21

Or if the number is 5: the sum will be 0 because we will not sum the right digit (in this example its also our only digit).

I tried to write the recursive function, but without success.

int sumDig(int num) {
    if (num < 10)
        return 0;
    return (num % 10 + sumDig(num / 10));
}

Thanks for everyone

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

The function you have written would print the sum of all digits of num except the first digit, which is the opposite of what you want to achieve. Consider the following function:-

    int sumDig(int num) {
        if (num > 0)
            return (num % 10 + sumDig(num / 10));
        else
            return 0;
    }

You can directly call this function with num/10 to achieve your use case. Alternatively, you can use a wrapper function.

over 4 years ago · Santiago Trujillo Denunciar

0

Because the base case is num<10, you're actually adding all except the most significant digit.

To get all except the last, this can be done by having the function grab the second-to-last digit and adding that to the result of the recursive call.

int sumDig(int num) {
    if (num == 0) {
        return 0;
    }
    return ((num / 10) % 10) + sumDig(num / 10);
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda