简体   繁体   中英

Add the number digits with recursion

I tried to add all the digits in a number but it only adds the first and the last digit. For example 1111 -> 1+1+1+1 = 4 but I got 2, 47879 -> 35 but I got 13, and so on...

Here's the code:

#include <iostream>
using namespace std;
int input(int &n)
{
    cin >> n;
    return 0;
}
int sum(int n, int &s)
{
    int left = n % 10;
    
    if (n < 10)
    {
        return left;
    }
    else
    { 
        s =s+ left + sum( n / 10, s);
    }
}
int main() {
    int n, s = 0;
    input(n);
    sum(n, s);
    cout << s;
}

Also, I can only use recursion; no string, no array, no loop, etc.

You can use this much simpler function:

constexpr int sum(int n) {
  return n ? n%10 + sum(n/10) : 0;
}

Or if you want it to be tail-recursive:

int sum(int n, int s = 0) {
  return n ? sum(n/10, s + n%10) : s;
}

In your implementation you never return on the else branch.

The function sum have return type of int. But in the recursion path some function calls does not return anything. (if else execute rather than if )

you can simply use this function:

void sum(int n, int &s)
{
    int left = n % 10;

    s += left;

    if (n < 10)
        return;
    else
        sum(n / 10, s);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM