Search⌘ K
AI Features

Solution Review: Sum of Digits in a String

Explore how to sum digits in a string using recursion in JavaScript. Understand the process of converting characters to integers, creating recursive calls, and defining base cases to solve this common coding interview problem effectively.

We'll cover the following...

Solution: Using Recursion

Javascript (babel-node)
function sumDigits(testVariable) {
// Base case
if (testVariable === "") {
return 0;
}
// Recursive case
else {
return Number(testVariable[0]) + sumDigits(testVariable.substr(1));
}
}
// Driver Code
myString = "345";
console.log(sumDigits(myString));

Explanation

The solution to this problem is similar to the solution of finding the ...