« Sum of digits recursively

Problem

Sum of digits recursively

Write a recursive function that returns the sum of the digits of a given integer.

Input format :

Integer N

Output format :

Sum of digits of N

Constraints :

0 <= N <= 10^9

Sample Input 1 :

12345

Sample Output 1 :

15

Sample Input 2 :

9

Sample Output 2 :

9

Solution

1#include <iostream>
2#include <iomanip>
3#include <algorithm>
4#include <string>
5#include <cstring>
6#include <vector>
7#include <cmath>
8#include <map>
9#include <climits>
10// climits for INT_MIN
11#include <unordered_map>
12using namespace std;
13
14int sumOfDigits(int n) {
15
16 if(n == 0){
17 return 0;
18 }
19
20 int x = sumOfDigits(n/10);
21 int r = n%10;
22 int sum = r + x;
23
24 return sum;
25}
26
27
28int main()
29{
30 int n;
31 cin >> n;
32 cout << sumOfDigits(n) << endl;
33 return 0;
34}