Recursion: Given a number, return the sum of digit

Problem Statement:

You are given a number, you need to return the sum of digits.

Example:

Input: n = 123
Output: 6

Solution Explanation:

We will use recursion to solve the problem.

Solution is to extract last digit and add it to the sum of digits and repeat the same till the number becomes 0.

Time Complexity: O(log n)
Space Complexity: O(log n)

Code Solution

#include <iostream>
#include <vector>
#include <queue>
#include <stack>
using namespace std;

int solution(int n) 
{
    
    // Base condition
    if (n == 0)
        return 0;

    return (n % 10) + solution(n / 10);
}

int main() {
    cout << solution(123);
    return 0;
}

Output

6
Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *