This post is completed by 4 users
|Add to List|
In a number, add digits until it becomes a single digit
Write a program to add the digits of the given number until the number becomes a single digit number.
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
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 are:
- When the input number is less than 10 then return the number.
Input: 256, Output: 4 Input: 15, Output: 6 Input: 82, Output: 1 Input: 242239, Output: 4