ratavagn
ratavagn

Reputation: 77

Transform this iteration function to recursive

This is a function to display the sum of the input digits with iteration perspective:

function sumOfDigits(number) {
    let strNumber = number.toString()
    let output = 0;
    for(i=0;i<strNumber.length;i++){
      let tmp = parseInt(strNumber[i])
      output = output + tmp
    }
    return output
}

// TEST CASES
console.log(sumOfDigits(512)); // 8
console.log(sumOfDigits(1542)); // 12
console.log(sumOfDigits(5)); // 5
console.log(sumOfDigits(21)); // 3
console.log(sumOfDigits(11111)); // 5

I am wondering how we write this function in a recursive way?

Upvotes: 1

Views: 53

Answers (3)

Athanasios Kataras
Athanasios Kataras

Reputation: 26362

I have not tested it, but you can try the following without casting to string

function sumOfDigits(number) 
{ 

    if (number === 0) {
       return 0; 
    }

    return (number % 10 + sumOfDigits(Math.floor(number / 10))); 
}

Make sure that the input is indeed in number format

Upvotes: 2

0bero
0bero

Reputation: 1062

Using the modulo operator, you can get the remainder (which in the case of a divison by 10, is the last number) and then add the next iteration.

function sumOfDigits (n) {
    if (n === 0) return 0
    return (n % 10 + sumOfDigits(Math.floor(n / 10)))
}

console.log(sumOfDigits(512))

If you want to see a more detailed explanation, check https://www.geeksforgeeks.org/sum-digit-number-using-recursion/

Upvotes: 2

Iren Saltalı
Iren Saltalı

Reputation: 536

Here you go

function sumOfDigitsRecursive(number){
    let strNumber = number.toString()
    if(strNumber.length<=0)
       return 0
    return parseInt(strNumber[0])+sumOfDigitsRecursive(strNumber.slice(1,strNumber.length))
}

Upvotes: 1

Related Questions