Count Total Digits in a Number in Javascript using recursion

 In this article we will use recursion to count total digits in a given number


function countDigits(n){

    if(n ==0){
        return n;
    }
 
   return 1+ countDigits(parseInt(n/10));
    
}

let sum= countDigits(999999);
console.log("result" + sum);

How this works

This is  how countDigits function is called

1+ countDigits(99999) returns 1 +4 = 5
    1+ countDigits(9999) returns 1 +3 = 4
        1+ countDigits(999) returns 1 +2 = 3
            1+ countDigits(99) returns 1 +1 = 2
                1+ countDigits(9) returns 1 +0 = 1
                     (n ==0) returns 0

First function keeps calling by passing argument then function keeps returning and at last will return 
the final result. 

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)