« 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_MIN11#include <unordered_map>12using namespace std;1314int sumOfDigits(int n) {1516 if(n == 0){17 return 0;18 }1920 int x = sumOfDigits(n/10);21 int r = n%10;22 int sum = r + x;2324 return sum;25}262728int main()29{30 int n;31 cin >> n;32 cout << sumOfDigits(n) << endl;33 return 0;34}