Sum of digits using Recursion in Javascript.

 Recursion in Javascript

function sumOfDigits(n){

    let num = parseInt(n/10); 
    let digit = n%10; 
    if(n ==0){
        return n;
    }
 
   return digit + sumOfDigits(num);
    
}

let sum= sumOfDigits(99999);
console.log("result"  + sum);

How this works

9 + sumOfDigits(9999) = returns 9 + 36  = 45
     9 + sumOfDigits(999) = returns 9 + 27  = 36
             9 + sumOfDigits(99)  = returns 9 + 18  = 27
                    9 + sumOfDigits(9)  = returns 9 + 9 = 18
                        9 + sumOfDigits(0)  = returns 9


So finally it returns 45, which is the sum of digits.

Comments

Popular posts from this blog

How to get and set a sublist in netsuite suitlet suitescript 2.0

Netsuite PHP Toolkit ADD Record Example ( SuiteTalk WebServices)