This post is completed by 3 users

  • 0
Add to List
Beginner

523. Add digits until the number becomes a single digit

Write a program to add the digits of the given number until the number becomes a single digit number.

This problem is also known as Find the Single Digit Sum of a Number

Example:

Input: 256, Output: 4
256 -> 13 -> 4

Input: 15, Output: 6
15 -> 6

Input: 82, Output: 1
82 -> 10 -> 1

Input: 242239, Output: 4
242239 -> 22 -> 4

Approach:

In this article, we are using recursion which can be easily modified to an iterative solution. I start with the given input number and find the sum of all its digits and make a recursive call with the input equal to the sum. Base cases is:

  • When the input number is less than 10 then return the number.

Complete Code:

 


Output:

Input: 256, Output: 4
Input: 15, Output: 6
Input: 82, Output: 1
Input: 242239, Output: 4