Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

198
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda