JavascriptWeb DevelopmentObject Oriented Programming
JavaScript for beginners
Best Seller
74 Lectures 10 hours
Lets Kode It
More Detail
Modern Javascript for Beginners + Javascript Projects
Most Popular
112 Lectures 15 hours
DigiFisk [Programming Is Fun]
More Detail
The Complete Full-Stack JavaScript Course!
Best Seller
96 Lectures 24 hours
Joseph Delgadillo
More Detail
Let’s say, we are required to create a function that takes in a number and finds the sum of its digits recursively until the sum is a one-digit number.
For example −
findSum[12345] = 1+2+3+4+5 = 15 = 1+5 = 6
So, the output should be 6.
Let’s write the code for this function findSum[] −
Example
// using recursion const findSum = [num] => { if[num < 10]{ return num; } const lastDigit = num % 10; const remainingNum = Math.floor[num / 10]; return findSum[lastDigit + findSum[remainingNum]]; } console.log[findSum[2568]];
We check if the number is less than 10, it’s already minified and we should return it and from the function otherwise we should return the call to the function that recursively takes the last digit from the number adds to it until it becomes less than 10.
Output
So, the output for this code will be −
3
AmitDiwan
Updated on 19-Aug-2020 07:02:55
- Related Questions & Answers
- Recursive product of all digits of a number - JavaScript
- Destructively Sum all the digits of a number in JavaScript
- Recursive sum of digits of a number formed by repeated appends in C++
- Recursive sum of digits of a number is prime or no in C++
- Prime digits sum of a number in JavaScript
- Recursive product of summed digits JavaScript
- Sorting digits of all the number of array - JavaScript
- Summing up all the digits of a number until the sum is one digit in JavaScript
- Digit sum upto a number of digits of a number in JavaScript
- Check if a number is magic [Recursive sum of digits is 1] in C++
- Product sum difference of digits of a number in JavaScript
- Program to find the sum of all digits of given number in Python
- Repeated sum of Number’s digits in JavaScript
- Checking whether the sum of digits of a number forms a Palindrome Number or not in JavaScript
- Sum a negative number [negative and positive digits] - JavaScript
Previous Page Print Page Next Page
Advertisements
I'm learning the basics of JavaScript and am trying to write a recursive function to add together a group of integers. For example, the function argument would be 1234
and the result should be 10
. Here's what I have so far...
function sumDigits[numbersStr] {
var numToString = numbersStr.toString[]
var numArr = numToString.split[''].map[Number];
var sum = 0;
// base case
if [numArr.length === 0] {
return sum
}
// recursive case
else {
var popped = numArr.pop[];
sum+=popped;
return sumDigits[numArr];
}
}
But I get an infinite loop whenever I run this [my tab crashes]. If I'm
popping the last element of an array, adding it to the sum
variable, then calling the function again on the shortened array, then why do I get an infinite loop? Many thanks!
asked Feb 20, 2018 at 20:41
e1v1se1v1s
3455 silver badges16 bronze badges
11
The problem in your code is that sumDigits expects to get a number, but in the recursion you pass an array of numbers to it.
answered Feb 20, 2018 at 20:49
YossiYossi
5,0796 gold badges34 silver badges70 bronze badges
5
You could use a string or number as argument of the function and convert the value to a string.
Then check the length and return zero if the length is zero [usualy the exit condition].
If not return the value of the fist character and add the result of calling the function with a sliced string from index one.
Basically a recurisve function have two parts.
The exit condition with an exit value. This depends on the purpose of the recursive function. It is usually a neutral value, like zero for addition, or
1
for multiplication.The actuall value plue a arithmetic operation and the call of the function again with a reduced string/array or numerical value.
function sumDigits[num] {
num = num.toString[];
return num.length === 0
? 0
: +num[0] + sumDigits[num.slice[1]];
}
console.log[sumDigits[1234]];
Another approach would be the use of tail recursion, which does not extend the
stack for each calling function, because the function ends with the call without keeping a temporary value liek in above function, the actual numerical value +num[0]
and the waiting for execution of the adition.
In this case, you could store the intermediate result along with the calling of the function.
function sumDigits[num, sum] { // num is expected to be a string
sum = sum || 0;
if [num.length === 0] {
return sum;
}
return sumDigits[num.slice[1], sum + +num[0]];
}
console.log[sumDigits['1234']];
answered Feb 20, 2018 at 20:49
Nina ScholzNina Scholz
359k24 gold badges321 silver badges364 bronze badges
0
function digitCount[num] {
let val1 = num % 10
let rem = Math.floor[num / 10]
return val1 + [rem != 0 ? digitCount[rem] : 0]
}
console.log[digitCount[87]]
answered Jun 7, 2021 at 14:49
4
The problem is that your function takes a number as it's argument, but when you use it recursively, you're giving it an array back. I would recommend pulling the recursive part into its own helper function like so:
function sumDigits[num] {
var numStr = num.toString[]
var numArr = numStr.split[''].map[Number];
function sumHelper[arr] {
// Base case:
if [arr.length === 1] {
return arr[0];
}
// Otherwise recurse [return last number plus the sum
// of the remainder]:
return arr.pop[] + sumHelper[arr];
}
// Then use that recursive helper:
return sumHelper[numArr];
}
console.log[sumDigits[1234]]
answered Feb 20, 2018 at 20:49
CRiceCRice
27.5k4 gold badges55 silver badges62 bronze badges
5
Your function expects a string, but on the recursive call, you pass it an array.
Additionally, you've got a call to .map
that isn't needed because you can convert the strings in the .split
array to numbers simply by prepending a +
to them.
Is there any reason you just don't use Array.reduce
?
function sumDigits[stringOfNums] {
// Split the string into an array of strings. Reduce the array to the sum by
// converting each string to a number.
console.log[stringOfNums.split[''].reduce[function[x,y]{ return +x + +y}, 0]];
}
sumDigits["1234"];
answered Feb 20, 2018 at 20:54
Scott MarcusScott Marcus
61.5k6 gold badges44 silver badges65 bronze badges
3
Passing an array in the recursive call will guarantee that its .toString[]
will never be empty because the commas will add more characters than have been removed.
Instead, do it mathematically so you don't need an array or even string conversion.
function sumDigits[num] {
return num ? [num%10] + sumDigits[Math.floor[num/10]] : 0
}
console.log[sumDigits[1234]]
This assumes a positive integer is passed. You'll need additional guards if other input could be provided.
answered Feb 20, 2018 at 20:58
There's
no need to convert the number to an array. You can get the last digit of a number with number % 10
, and remove that digit with Math.floor[number / 10]
. Then recurse until the number is 0
.
function sumDigits[num] {
if [num == 0] {
return 0;
} else {
var last = num % 10;
var rest = Math.floor[num / 10];
return last + sumDigits[rest];
}
}
console.log[sumDigits[1234]];
answered Feb 20, 2018 at 20:59
BarmarBarmar
694k53 gold badges468 silver badges576 bronze badges
Barmar has a good voice of reason. Converting from number to string then converting back to number again is a bit silly. Plus, if this is a homework assignment, using high-level
functions like String.prototype.split
probably won't teach you much.
Here's a tail-recursive version Barmar's program written using functional style
- base case - the input number
n
is zero, return the accumulatoracc
- inductive case -
n
is not zero; recur with the nextn
and the nextacc
const sumDigits = [n = 0, acc = 0] =>
n === 0
? acc
: sumDigits [n / 10 >> 0, acc + n % 10]
console.log [sumDigits []] // 0
console.log [sumDigits [1]] // 1
console.log [sumDigits [12]] // 3
console.log [sumDigits [123]] // 6
console.log [sumDigits [1234]] // 10
answered Feb 20, 2018 at 22:09
MulanMulan
123k29 gold badges217 silver badges249 bronze badges